diff --git a/.github/workflows/import.yml b/.github/workflows/import.yml index 5dd2555..9adbffc 100644 --- a/.github/workflows/import.yml +++ b/.github/workflows/import.yml @@ -7,6 +7,8 @@ name: Import members # dry-run restore, extract and check everything; nothing is written to the site # load the real import (safe to repeat: it updates rather than duplicates) # remove take every imported member off the site again (demo data and new sign-ups stay) +# risk-check one-time clean-up: put members whose old-site sign-in countries don't fit their +# profile country in Moderation ("Sign-in location"). Changes nothing else. Same backups as load. # # Real member data goes to prod. Use dev for test runs. on: @@ -25,7 +27,7 @@ on: mode: description: What to do type: choice - options: [dry-run, load, remove] + options: [dry-run, load, remove, risk-check] default: dry-run legacy_backup: description: Old site SQL Server backup in the imports container (blank to skip) @@ -112,7 +114,9 @@ jobs: - name: Extract the old site if: ${{ inputs.mode != 'remove' && inputs.legacy_backup != '' }} - run: npm run import -w @whatbox/api -- extract-legacy --site "$SITE" --out "$WORK/bundles/2-legacy" | tee -a "$WORK/extract.txt" + run: | + photos=(); [ "$MODE" = risk-check ] && photos=(--photos false) + npm run import -w @whatbox/api -- extract-legacy --site "$SITE" --out "$WORK/bundles/2-legacy" "${photos[@]}" | tee -a "$WORK/extract.txt" env: SOURCE_MSSQL: Server=localhost,1433;Database=legacy;User Id=sa;Password=${{ env.SA_PW }};Encrypt=true;TrustServerCertificate=true @@ -133,7 +137,7 @@ jobs: - name: Extract SkaDate if: ${{ inputs.mode != 'remove' && inputs.skadate_dump != '' }} run: | - photos=(); [ -d "$WORK/userfiles" ] && photos=(--photos "$WORK/userfiles") + photos=(); [ -d "$WORK/userfiles" ] && [ "$MODE" != risk-check ] && photos=(--photos "$WORK/userfiles") npm run import -w @whatbox/api -- extract-skadate --out "$WORK/bundles/1-skadate" "${photos[@]}" | tee -a "$WORK/extract.txt" env: SOURCE_MYSQL: mysql://root:${{ env.MY_PW }}@127.0.0.1:3306/skadate @@ -153,6 +157,7 @@ jobs: dry-run) args=(load --site "$SITE" --bundle "blob:$PREFIX" --dry-run --report-blob "$report") ;; load) args=(load --site "$SITE" --bundle "blob:$PREFIX" --report-blob "$report") ;; remove) args=(remove --site "$SITE" --report-blob "$report") ;; + risk-check) args=(risk-check --site "$SITE" --bundle "blob:$PREFIX" --report-blob "$report") ;; esac # The job reads (and deletes) this file, so its own settings and secrets stay untouched. printf '%s\n' "${args[@]}" | jq -R . | jq -sc '{args: .}' > "$RUNNER_TEMP/next.json" diff --git a/apps/api/package.json b/apps/api/package.json index 0bfb222..1f84cdc 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -30,6 +30,7 @@ "@whatbox/core": "^0.1.0", "all-the-cities": "3.1.0", "jose": "^6.2.18", + "mmdb-lib": "^3.0.5", "mssql": "^12.8.3", "mysql2": "^3.24.6", "pg": "^8.23.1", diff --git a/apps/api/scripts/import.ts b/apps/api/scripts/import.ts index 296858a..948d5cf 100644 --- a/apps/api/scripts/import.ts +++ b/apps/api/scripts/import.ts @@ -11,6 +11,12 @@ // remove deletes every imported member on a site (not demo data, not real sign-ups) // npm run import -w @whatbox/api -- remove --site afterh [--dry-run] // +// risk-check one-time clean-up: queues members whose old-site sign-in countries don't fit the +// country on their profile ("Sign-in location" in Moderation). Changes nothing else. +// npm run import -w @whatbox/api -- risk-check --site afterh --bundle [--bundle ] [--dry-run] +// Extracts look sign-in IPs up in DB-IP Lite (downloaded then; --no-ip-check skips it) and keep only +// the derived countries in the bundle, never the IPs. +// // In Azure (the "Import members" workflow), --bundle blob: reads bundles from the private // "imports" container, and --report-blob writes the counts back there for the workflow summary. // @@ -27,7 +33,8 @@ import { PgControlRepo, PgSiteRepo, siteDbName } from '../src/pg-repo'; import { createPhotoStore } from '../src/photos'; import { readBundle } from '../src/import/bundle'; import { extractLegacy, LEGACY_SITES, type LegacySite } from '../src/import/legacy'; -import { loadBundles, removeImported } from '../src/import/load'; +import { loadBundles, removeImported, riskCheckImported } from '../src/import/load'; +import { LocalIpIntel } from '../src/ipintel'; import { extractSkadate } from '../src/import/skadate'; function args(argv: string[]) { @@ -87,7 +94,7 @@ async function argsFromBlob(): Promise { const blob = importsContainer().getBlockBlobClient('jobs/next.json'); const task = JSON.parse((await blob.downloadToBuffer()).toString('utf8')) as { args: string[] }; await blob.delete(); // single use - if (!Array.isArray(task.args) || !['load', 'remove'].includes(task.args[0])) throw new Error('jobs/next.json must hold {"args": ["load" | "remove", ...]}'); + if (!Array.isArray(task.args) || !['load', 'remove', 'risk-check'].includes(task.args[0])) throw new Error('jobs/next.json must hold {"args": ["load" | "remove" | "risk-check", ...]}'); return task.args.map(String); } @@ -97,20 +104,26 @@ async function argsFromBlob(): Promise { const [cmd, ...rest] = argv; const a = args(rest); const dryRun = a['dry-run']?.[0] === 'true'; + const ipIntel = async () => { + if (a['no-ip-check']) return undefined; + const i = new LocalIpIntel({ tor: false, countryUrl: config.geoipCountryUrl || undefined, asnUrl: config.geoipAsnUrl || undefined }); + if (!(await i.loadNow())) console.warn('IP country database did not load: sign-in countries are left out of this bundle.'); + return i; + }; if (cmd === 'extract-legacy') { const site = one(a, 'site') as LegacySite; if (!LEGACY_SITES.includes(site)) throw new Error(`--site must be one of ${LEGACY_SITES.join(', ')}`); const conn = process.env.SOURCE_MSSQL; if (!conn) throw new Error('Set SOURCE_MSSQL to the restored database connection string.'); - const info = await extractLegacy(site, conn, one(a, 'out')); + const info = await extractLegacy(site, conn, one(a, 'out'), { photos: a.photos?.[0] !== 'false', ipIntel: await ipIntel() }); console.log(JSON.stringify({ source: info.source, site: info.site, counts: info.counts, skipped: info.skipped }, null, 2)); return; } if (cmd === 'extract-skadate') { const url = process.env.SOURCE_MYSQL; if (!url) throw new Error('Set SOURCE_MYSQL to mysql://user:pass@host:3306/database'); - const info = await extractSkadate(url, one(a, 'out'), { photosDir: one(a, 'photos', false) || undefined }); + const info = await extractSkadate(url, one(a, 'out'), { photosDir: one(a, 'photos', false) || undefined, ipIntel: await ipIntel() }); console.log(JSON.stringify({ source: info.source, site: info.site, counts: info.counts, skipped: info.skipped }, null, 2)); return; } @@ -130,7 +143,7 @@ async function argsFromBlob(): Promise { if (name) await importsContainer().getBlockBlobClient(name).upload(text, Buffer.byteLength(text), { blobHTTPHeaders: { blobContentType: 'application/json' } }); }; try { - if (cmd === 'load') { + if (cmd === 'load' || cmd === 'risk-check') { const given: string[] = []; for (const b of a.bundle ?? []) { if (!b.startsWith('blob:')) { given.push(b); continue; } @@ -141,14 +154,13 @@ async function argsFromBlob(): Promise { if (!dirs.length) throw new Error('Give at least one --bundle folder.'); const bundles = []; for (const d of dirs) bundles.push(await readBundle(d)); - const report = await loadBundles(bundles, { - site, repo, crypto: new SiteCrypto(keyProvider(), site.id), geo: new WorldGeo(), photos, now: new Date(), dryRun, - }); - await output(report); + const crypto = new SiteCrypto(keyProvider(), site.id); + if (cmd === 'risk-check') await output(await riskCheckImported(bundles, { site, repo, crypto, now: new Date(), dryRun })); + else await output(await loadBundles(bundles, { site, repo, crypto, geo: new WorldGeo(), photos, now: new Date(), dryRun })); } else if (cmd === 'remove') { await output(await removeImported(repo, site, photos, dryRun)); } else { - throw new Error('Usage: import extract-legacy | extract-skadate | load | remove (see the top of scripts/import.ts)'); + throw new Error('Usage: import extract-legacy | extract-skadate | load | remove | risk-check (see the top of scripts/import.ts)'); } } finally { if (tmp) await rm(tmp, { recursive: true, force: true }); // the downloaded bundle holds member data diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 738bd6c..750e636 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -58,7 +58,7 @@ export class PublicController extends SiteScoped { return this.p.signInWithProvider(await this.site(r), b.provider, String(b.idToken ?? ''), { ip: r.ip }); } @Post('auth/verify') async verify(@Req() r: Request, @Body() b: { challengeId: string; code: string }) { - return this.p.verifyCode(await this.site(r), String(b.challengeId), String(b.code)); + return this.p.verifyCode(await this.site(r), String(b.challengeId), String(b.code), { ip: r.ip }); } @Post('auth/sign-out') async signOut(@Req() r: Request) { const t = bearer(r.headers.authorization); diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index b917cc7..5b4ef7f 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -32,6 +32,11 @@ export const config = { paymentsStub: process.env.PAYMENTS_STUB === 'true', // dev only: pretend processor with a /dev/checkout page allowSelfServeTier: process.env.ALLOW_SELF_SERVE_TIER === 'true', // dev only: switch tier without paying azureStorageJson: process.env.AZURE_STORAGE_JSON ?? '', // optional storage account per site + // Sign-in risk hints: local IP databases, downloaded by the API itself (see ipintel.ts). on | off + geoip: (process.env.GEOIP ?? 'on') as 'on' | 'off', + geoipCountryUrl: process.env.GEOIP_COUNTRY_URL ?? '', // default: DB-IP Country Lite for this month + geoipAsnUrl: process.env.GEOIP_ASN_URL ?? '', // default: DB-IP ASN Lite for this month + geoipTor: process.env.GEOIP_TOR !== 'false', // Tor Project exit list }; export function dbUrl(dbName: string) { diff --git a/apps/api/src/db.ts b/apps/api/src/db.ts index 77601f3..241da86 100644 --- a/apps/api/src/db.ts +++ b/apps/api/src/db.ts @@ -9,6 +9,7 @@ import { createNotifier } from './notify'; import { createIdTokenVerifier } from './idp'; import { createPaymentGateways } from './payments'; import { PgSiteProvisioner } from './provision'; +import { createIpIntel } from './ipintel'; export { pool, closePools } from './db-pool'; @@ -28,7 +29,8 @@ export function keyProvider(): KeyProvider { } -export function createPlatform() { +/** ipIntel: download the sign-in IP databases (the API server only; one-off scripts skip it). */ +export function createPlatform(opts: { ipIntel?: boolean } = {}) { const control = new PgControlRepo(pool(config.controlDb)); const siteRepos = new Map(); const photos = createPhotoStore(); @@ -57,6 +59,7 @@ export function createPlatform() { provisioner: new PgSiteProvisioner(), allowSelfServeTier: config.allowSelfServeTier && process.env.NODE_ENV !== 'production', geo: new WorldGeo(), + ipIntel: opts.ipIntel ? createIpIntel() : undefined, }); return { platform, control, photos, events }; } diff --git a/apps/api/src/import/bundle.ts b/apps/api/src/import/bundle.ts index 2f430cf..760b001 100644 --- a/apps/api/src/import/bundle.ts +++ b/apps/api/src/import/bundle.ts @@ -10,6 +10,7 @@ // Keep it only in the private "imports" storage container or a temporary folder, never in git. import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; +import type { MemberNetwork } from '@whatbox/core'; import type { Gender, PhotoKind } from '@whatbox/core'; export type SourceKind = 'aspnetdating' | 'skadate'; @@ -43,6 +44,8 @@ export interface SrcMember { /** Things a moderator should look at, e.g. "not_approved" or "spam_suspected" on the old site. */ flags: string[]; photos: SrcPhoto[]; + /** Countries and VPN/hosting networks the old site logged them signing in from. Derived; never the IPs. */ + network?: MemberNetwork; } export type SrcRelation = diff --git a/apps/api/src/import/legacy.ts b/apps/api/src/import/legacy.ts index d35ac50..2e5a2be 100644 --- a/apps/api/src/import/legacy.ts +++ b/apps/api/src/import/legacy.ts @@ -2,10 +2,12 @@ // Reads a restored SQL Server copy of the backup and writes a bundle. Never writes to the source. // // Not carried over: passwords (the new platform signs in with an emailed code), real names, -// IP addresses, billing details, chat rooms, blogs, ratings, deleted accounts and couple profiles. +// IP addresses (only the country and network type derived from them, see network.ts), billing details, chat rooms, blogs, ratings, deleted accounts and couple profiles. import sql from 'mssql'; import { writeFile } from 'node:fs/promises'; import { normalizeImage } from '../photos'; +import type { LocalIpIntel } from '../ipintel'; +import { networkFromHistory } 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, @@ -19,14 +21,14 @@ export const LEGACY_SITES: LegacySite[] = ['afterh', 'hfriends', 'datealittle']; const DELETED_FOLDER = 2147483647; const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; -export async function extractLegacy(site: LegacySite, connectionString: string, outDir: string, opts: { photos?: boolean } = {}) { +export async function extractLegacy(site: LegacySite, connectionString: string, outDir: string, opts: { photos?: boolean; ipIntel?: LocalIpIntel } = {}) { if (!LEGACY_SITES.includes(site)) throw new Error('Unknown legacy site ' + site); await prepareBundleDir(outDir); const pool = await new sql.ConnectionPool(connectionString).connect(); const q = async (text: string) => (await pool.request().query(text)).recordset as T[]; const info: BundleInfo = { source: 'aspnetdating', site, extractedAt: new Date().toISOString(), counts: {}, skipped: {} }; try { - const users = await q(`SELECT u_username, u_email, u_gender, u_interested_in, u_birthdate, u_usersince, u_lastonline, u_lastlogin, + const users = await q(`SELECT u_username, u_email, u_gender, u_interested_in, u_birthdate, u_usersince, u_lastonline, u_lastlogin, u_signup_ip, u_country, u_state, u_city, u_zip_code, u_latitude, u_longitude, u_deleted, u_spamsuspected FROM Users`); const answers = new Map>(); for (const a of await q(`SELECT u_username, pq_id, pa_value FROM ProfileAnswers`)) { @@ -89,6 +91,23 @@ export async function extractLegacy(site: LegacySite, connectionString: string, const byKey = new Map(members.map((m) => [m.key, m])); const key = (u: string) => 'legacy:' + String(u).toLowerCase(); + // Sign-in countries from the old IP log, looked up here; the IPs themselves stay behind. + if (opts.ipIntel?.ready) { + const hist = new Map(); + 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) }); + } + 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'); + } + } else bump(info.skipped, 'sign-in country check (IP database not loaded)'); + // Photos are stored inside the database. Main first, then in upload order. const albums = new Map((await q(`SELECT pa_id, pa_access FROM PhotoAlbums`)).map((r) => [r.pa_id, r.pa_access])); const photoRows = await q(`SELECT p_id, u_username, pa_id, p_approved, p_primary, p_explicit, p_private, p_approvedtimestamp FROM Photos ORDER BY u_username, p_primary DESC, p_id`); diff --git a/apps/api/src/import/load.ts b/apps/api/src/import/load.ts index 601bb3c..ff2a7d3 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, type Gender, type GeoPlace, type GeoProvider, isGender, type Member, type ModerationItem, type Photo, type PhotoKind, + findContactInfo, type Gender, type MemberNetwork, 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'; @@ -57,6 +57,7 @@ export function mergeMembers(bundles: Bundle[]): MergedMember[] { m.createdAt = minIso(m.createdAt, src.createdAt); m.lastActiveAt = maxIso(m.lastActiveAt, src.lastActiveAt); m.flags = [...new Set([...m.flags, ...src.flags])]; + m.network = mergeNetworks(m.network, src.network); cur.photos.push(...photos); } } @@ -267,6 +268,74 @@ export async function loadBundles(bundles: Bundle[], d: LoadDeps): Promise [c.code, { ...c }])); + for (const c of b.countries) { + const cur = by.get(c.code); + if (!cur) by.set(c.code, { ...c }); + else { cur.count += c.count; if (c.lastAt > cur.lastAt) cur.lastAt = c.lastAt; } + } + const hosting = [a.hosting, b.hosting].filter((h): h is NonNullable => !!h).sort((x, y) => y.lastAt.localeCompare(x.lastAt))[0]; + const torAt = [a.torAt, b.torAt].filter(Boolean).sort().pop(); + return { countries: [...by.values()].sort((x, y) => y.count - x.count), ...(hosting ? { hosting } : {}), ...(torAt ? { torAt } : {}) }; +} + +export interface RiskCheckReport { + site: string; + dryRun: boolean; + members: Record; + /** Flagged members by the country they signed in from (counts only). */ + flaggedFrom: Record; +} + +/** + * One-time clean-up: compares where old-site members signed in from with the country on their + * profile here, and puts the ones that don't fit in the moderation queue ("Sign-in location"). + * Changes nothing else: no profile text, no status, nobody suspended. The sign-in countries are + * used for the check and not stored on the member. Safe to repeat: an item is raised once per + * member, and "Looks fine" or an open item is respected. + */ +export async function riskCheckImported(bundles: Bundle[], d: Pick): Promise { + for (const b of bundles) { + if (b.info.site !== d.site.slug) throw new Error(`This bundle is for "${b.info.site}", not "${d.site.slug}". Sites never share data.`); + } + const report: RiskCheckReport = { site: d.site.slug, dryRun: d.dryRun, members: {}, flaggedFrom: {} }; + for (const g of mergeMembers(bundles)) { + const m = await d.repo.findMemberByHash('email', await d.crypto.lookupHash(g.email)); + if (!m) { bump(report.members, 'not on the site'); continue; } + bump(report.members, 'checked'); + if (!g.m.network?.countries.length) bump(report.members, 'no sign-in IP to check (profile text still checked)'); + if (!m.country) bump(report.members, 'no country on their profile yet'); + // new-site sign-ins count too: someone seen at home here is not flagged for old travel + const view = { country: m.country, network: mergeNetworks(g.m.network, m.network), about: m.about }; + const key = riskKey(view); + if (!key) { + bump(report.members, riskFlags(view).length ? 'fits their profile (VPN or hosting seen, 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 (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(' ')}`, + }); + await d.repo.saveMember({ ...m, risk: { ...m.risk, openItemId: id } }); + } + return report; +} + /** Removes every imported member (and, through the database, their photos, likes and messages). Demo and real sign-ups are untouched. */ export async function removeImported(repo: SiteRepo, site: Site, photos: PhotoStore | undefined, dryRun: boolean) { let removed = 0; diff --git a/apps/api/src/import/network.ts b/apps/api/src/import/network.ts new file mode 100644 index 0000000..bec24ec --- /dev/null +++ b/apps/api/src/import/network.ts @@ -0,0 +1,42 @@ +// Sign-in countries for old-site members, for a one-time "does this fit their profile?" check. +// 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 type { MemberNetwork } from '@whatbox/core'; +import type { LocalIpIntel } from '../ipintel'; + +/** At most this many countries per member, most used first, so their home country is never cut off. */ +const MAX = 10; + +/** Old IPs are often stored as numbers (MySQL INET_ATON / ip2long). */ +export function ipFromLegacy(v: unknown): string | null { + if (typeof v === 'number' || (typeof v === 'string' && /^\d{5,10}$/.test(v))) { + const n = Number(v); + if (!Number.isFinite(n) || n <= 0 || n > 0xffffffff) return null; + return [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join('.'); + } + const s = String(v ?? '').trim(); + return s && s.length <= 45 ? s : null; +} + +export function networkFromHistory(rows: { ip: unknown; at?: string | null; count?: number }[], intel: LocalIpIntel): MemberNetwork | undefined { + const byCountry = new Map(); + let hosting: { org: string; lastAt: string } | undefined; + for (const r of rows) { + const ip = ipFromLegacy(r.ip); + if (!ip) continue; + const info = intel.lookup(ip); + if (!info) continue; + const at = r.at || new Date(0).toISOString(); + if (info.country) { + const c = byCountry.get(info.country) ?? { code: info.country, count: 0, lastAt: at }; + c.count += r.count ?? 1; + if (at > c.lastAt) c.lastAt = at; + byCountry.set(info.country, c); + } + if (info.hosting && info.org && (!hosting || at > hosting.lastAt)) hosting = { org: info.org, lastAt: at }; + } + const countries = [...byCountry.values()].sort((a, b) => b.count - a.count || b.lastAt.localeCompare(a.lastAt)).slice(0, MAX); + if (!countries.length && !hosting) return undefined; + return hosting ? { countries, hosting } : { countries }; +} diff --git a/apps/api/src/import/skadate.ts b/apps/api/src/import/skadate.ts index 0921e7d..fa8ba35 100644 --- a/apps/api/src/import/skadate.ts +++ b/apps/api/src/import/skadate.ts @@ -7,6 +7,8 @@ import mysql from 'mysql2/promise'; 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 { bump, type BundleInfo, type SrcMember, type SrcPhoto, type SrcRelation, photoPath, prepareBundleDir, writeBundle } from './bundle'; import { countBundle } from './legacy'; import { @@ -41,7 +43,7 @@ function findFile(idx: Map, prefixes: string[]): string | undefi return undefined; } -export async function extractSkadate(url: string, outDir: string, opts: { photosDir?: string } = {}) { +export async function extractSkadate(url: string, outDir: string, opts: { photosDir?: string; ipIntel?: LocalIpIntel } = {}) { await prepareBundleDir(outDir); const db = await mysql.createConnection({ uri: url, dateStrings: false, supportBigNumbers: true, bigNumberStrings: false }); const q = async (text: string) => (await db.query(text))[0] as T[]; @@ -105,6 +107,18 @@ export async function extractSkadate(url: string, outDir: string, opts: { photos } const byId = new Map(members.map((m) => [Number(m.key.slice(8)), m])); + // Oxwall keeps the IP each member joined from (as a number). Only the derived country goes in the bundle. + 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)'); } + 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'); + } + } else bump(info.skipped, 'sign-in country check (IP database not loaded)'); + // Photos: the avatar becomes the main photo, then album photos in upload order. const files = await fileIndex(opts.photosDir); const addPhoto = async (m: SrcMember, path: string | undefined, file: string, p: Omit) => { diff --git a/apps/api/src/ipintel.ts b/apps/api/src/ipintel.ts new file mode 100644 index 0000000..d77b8a3 --- /dev/null +++ b/apps/api/src/ipintel.ts @@ -0,0 +1,139 @@ +// Sign-in IP lookups for risk hints, done entirely on our own server: member IPs are never sent anywhere. +// The API downloads free databases into memory and refreshes them in the background: +// - DB-IP "IP to Country Lite" and "IP to ASN Lite" (CC BY 4.0, no account needed; credited in Owner Admin). +// https://db-ip.com/db/lite.php Updated monthly. +// - The Tor Project's public list of exit nodes. https://check.torproject.org/torbulkexitlist +// GEOIP_COUNTRY_URL / GEOIP_ASN_URL can point at other copies instead, e.g. MaxMind GeoLite2 (needs a free +// MaxMind account and licence key) or a copy in our own Blob storage. Plain .mmdb, .mmdb.gz and .tar.gz all work. +// If a download fails, lookups simply return less (or nothing) and sign-in carries on as normal. +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 { config } from './config'; + +type CountryRec = CountryResponse; +type AsnRec = AsnResponse; + +const DAY = 86_400_000; + +/** DB-IP publishes one file per month; early in a month the new one may not be out yet. */ +function dbipUrls(kind: 'country' | 'asn', now = new Date()): string[] { + const ym = (d: Date) => `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`; + const prev = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1)); + return [now, prev].map((d) => `https://download.db-ip.com/free/dbip-${kind}-lite-${ym(d)}.mmdb.gz`); +} + +/** Returns the .mmdb bytes from a plain, gzipped or tar.gz download. */ +export function unpackMmdb(buf: Buffer): Buffer { + let b = buf; + if (b[0] === 0x1f && b[1] === 0x8b) b = gunzipSync(b); + if (b.length > 512 && b.toString('latin1', 257, 262) === 'ustar') { + for (let off = 0; off + 512 <= b.length;) { + const name = b.toString('utf8', off, off + 100).replace(/\0.*$/s, ''); + if (!name) break; + const size = parseInt(b.toString('latin1', off + 124, off + 136).replace(/\0.*$/s, '').trim() || '0', 8); + if (name.endsWith('.mmdb')) return b.subarray(off + 512, off + 512 + size); + off += 512 + Math.ceil(size / 512) * 512; + } + throw new Error('no .mmdb file in the archive'); + } + return b; +} + +/** Addresses that are never a member's real network. */ +function isPrivate(ip: string) { + return /^(10\.|127\.|0\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(ip) + || ip === '::1' || /^(fc|fd|fe80)/i.test(ip); +} + +export class LocalIpIntel implements IpIntel { + private country: Reader | null = null; + private asn: Reader | null = null; + private tor = new Set(); + private timers: NodeJS.Timeout[] = []; + + constructor(private opts: { countryUrl?: string; asnUrl?: string; tor: boolean; fetch?: typeof fetch } = { tor: true }) {} + + /** Loads everything once now, then refreshes in the background (databases weekly, Tor list every 6 hours). */ + start() { + void this.loadDatabases(); + if (this.opts.tor) void this.loadTor(); + this.timers.push(setInterval(() => void this.loadDatabases(), 7 * DAY).unref()); + if (this.opts.tor) this.timers.push(setInterval(() => void this.loadTor(), DAY / 4).unref()); + return this; + } + stop() { for (const t of this.timers) clearInterval(t); } + + /** One-off tools: load the databases (no Tor list, no refresh) and wait. True when the country database loaded. */ + async loadNow() { await this.loadDatabases(); return this.ready; } + + /** For tests and tools: use databases already in hand. */ + useDatabases(country?: Buffer, asn?: Buffer, torExits?: string[]) { + if (country) this.country = new Reader(unpackMmdb(country)); + if (asn) this.asn = new Reader(unpackMmdb(asn)); + if (torExits) this.tor = new Set(torExits); + return this; + } + + get ready() { return !!this.country; } + + lookup(rawIp: string): NetworkInfo | null { + const ip = rawIp.replace(/^::ffff:/i, ''); + if (!isIP(ip) || isPrivate(ip)) return null; + const out: NetworkInfo = {}; + try { + const c = this.country?.get(ip); + // GeoIP2 layout (DB-IP, MaxMind), or the flat country_code some free copies use + const code = c?.country?.iso_code ?? c?.registered_country?.iso_code ?? (c as { country_code?: string } | null)?.country_code; + if (code && /^[A-Z]{2}$/.test(code) && code !== 'ZZ') out.country = code; + } catch { /* bad address for this database */ } + try { + const a = this.asn?.get(ip); + 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); + } + } catch { /* ignore */ } + if (this.tor.has(ip)) out.tor = true; + return out.country || out.asn || out.tor ? out : null; + } + + private async download(urls: string[]): Promise { + const f = this.opts.fetch ?? fetch; + let last: unknown; + for (const url of urls) { + try { + const res = await f(url, { signal: AbortSignal.timeout(120_000) }); + if (!res.ok) { last = new Error(`HTTP ${res.status}`); continue; } + return Buffer.from(await res.arrayBuffer()); + } catch (e) { last = e; } + } + throw last instanceof Error ? last : new Error('download failed'); + } + + private async loadDatabases() { + const jobs: [string, string[], (b: Buffer) => void][] = [ + ['country', this.opts.countryUrl ? [this.opts.countryUrl] : dbipUrls('country'), (b) => { this.country = new Reader(unpackMmdb(b)); }], + ['asn', this.opts.asnUrl ? [this.opts.asnUrl] : dbipUrls('asn'), (b) => { this.asn = new Reader(unpackMmdb(b)); }], + ]; + for (const [name, urls, use] of jobs) { + try { use(await this.download(urls)); console.log(`[ipintel] ${name} database loaded`); } + catch (e) { console.warn(`[ipintel] ${name} database not loaded: ${(e as Error).message}. Sign-in risk hints are limited until it loads.`); } + } + } + + private async loadTor() { + try { + const text = (await this.download(['https://check.torproject.org/torbulkexitlist'])).toString('utf8'); + const ips = text.split(/\s+/).filter((x) => isIP(x)); + if (ips.length) this.tor = new Set(ips); + } catch (e) { console.warn(`[ipintel] Tor exit list not loaded: ${(e as Error).message}`); } + } +} + +export function createIpIntel(): IpIntel | undefined { + if (config.geoip === 'off') return undefined; + return new LocalIpIntel({ countryUrl: config.geoipCountryUrl || undefined, asnUrl: config.geoipAsnUrl || undefined, tor: config.geoipTor }).start(); +} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index a2a8869..9939310 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -8,7 +8,7 @@ import { LocalPhotoStore } from './photos'; import { startCleanup } from './cleanup'; async function main() { - const { platform, photos, events, control } = createPlatform(); + const { platform, photos, events, control } = createPlatform({ ipIntel: true }); const app = await NestFactory.create(buildModule(platform), { bodyParser: false, logger: ['error', 'warn', 'log'] }); app.use(json({ limit: config.photoStore === 'inline' ? '8mb' : '256kb' })); app.useGlobalFilters(new ErrorFilter()); diff --git a/apps/api/src/pg-repo.ts b/apps/api/src/pg-repo.ts index 26ecd40..58ee8fb 100644 --- a/apps/api/src/pg-repo.ts +++ b/apps/api/src/pg-repo.ts @@ -5,6 +5,7 @@ import type { Message, ModerationItem, Photo, PrivateAccess, PushToken, Report, ReviewStatus, Site, SiteKpiRaw, SiteRepo, Subscription, TrafficHit, UsageKind, AuditEntry, VerificationChallenge, View, } from '@whatbox/core'; import type { Pool } from 'pg'; +import { NETWORK_KEEP_DAYS } from '@whatbox/core'; const docs = (rows: { doc: T }[]) => rows.map((r) => r.doc); @@ -240,6 +241,11 @@ export class PgSiteRepo implements SiteRepo { await this.db.query('DELETE FROM challenges WHERE expires_at < $1', [now]); await this.db.query("DELETE FROM subscriptions WHERE status='pending' AND created_at < $1::timestamptz - interval '2 days'", [now]); await this.db.query("DELETE FROM webhook_events WHERE at < $1::timestamptz - interval '90 days'", [now]); + // Sign-in countries are only kept while recent (see NETWORK_KEEP_DAYS); members who stopped signing in lose them. + await this.db.query( + `UPDATE members SET doc = doc - 'network' WHERE doc ? 'network' AND GREATEST(doc#>>'{network,countries,0,lastAt}', doc#>>'{network,hosting,lastAt}', doc#>>'{network,torAt}')::timestamptz < $1::timestamptz - make_interval(days => $2)`, + [now, NETWORK_KEEP_DAYS], + ); const r = await this.db.query( "UPDATE subscriptions SET status='expired', updated_at=$1 WHERE status='cancelled' AND period_end < $1 RETURNING member_id", [now], ); diff --git a/apps/api/test/ipintel.test.ts b/apps/api/test/ipintel.test.ts new file mode 100644 index 0000000..835c8e5 --- /dev/null +++ b/apps/api/test/ipintel.test.ts @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { gzipSync } from 'node:zlib'; +import { LocalIpIntel, unpackMmdb } from '../src/ipintel'; + +function tar(name: string, body: Buffer) { + const h = Buffer.alloc(512); + h.write(name, 0, 'utf8'); + h.write(body.length.toString(8).padStart(11, '0') + '\0', 124, 'latin1'); + h.write('ustar', 257, 'latin1'); + const pad = Buffer.alloc(Math.ceil(body.length / 512) * 512 - body.length); + return Buffer.concat([h, body, pad]); +} + +test('database downloads unpack from .mmdb, .mmdb.gz and MaxMind-style .tar.gz', () => { + const body = Buffer.from('pretend mmdb bytes'); + assert.deepEqual(unpackMmdb(body), body); + assert.deepEqual(unpackMmdb(gzipSync(body)), body); + const archive = Buffer.concat([tar('GeoLite2-Country_20261126/COPYRIGHT.txt', Buffer.from('c')), tar('GeoLite2-Country_20261126/GeoLite2-Country.mmdb', body), Buffer.alloc(1024)]); + assert.deepEqual(unpackMmdb(gzipSync(archive)), body); +}); + +test('without databases, lookups return nothing except Tor; private addresses are skipped', () => { + const i = new LocalIpIntel({ tor: false }).useDatabases(undefined, undefined, ['185.220.101.1']); + assert.equal(i.lookup('73.0.0.1'), null); + assert.deepEqual(i.lookup('::ffff:185.220.101.1'), { tor: true }); + assert.equal(i.lookup('10.1.2.3'), null); + assert.equal(i.lookup('not an ip'), null); +}); diff --git a/apps/member/src/app/admin/index.tsx b/apps/member/src/app/admin/index.tsx index 342f744..3d7abec 100644 --- a/apps/member/src/app/admin/index.tsx +++ b/apps/member/src/app/admin/index.tsx @@ -3,7 +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 ProfileFieldDef, type Site, type SiteStats, type SiteTheme, TIERS, type Tier, type TierPerms, + type ProfileFieldDef, type RiskFlag, 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'; @@ -258,6 +258,7 @@ 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 [openId, setOpenId] = 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(); }; @@ -266,6 +267,7 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; message: ['Held message', 'Release to recipient', 'Keep blocked'], report: ['Member report', 'Suspend member', 'Dismiss'], profile: ['Profile text', 'Looks fine', 'Clear all of "About me"'], + risk: ['Possible scammer', 'Looks fine', 'Suspend member'], }; 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 () => { @@ -289,7 +291,7 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; ) : null} {recheck.note ? {recheck.note} : null} - {!items ? : items.length === 0 ? Nothing waiting. New uploads, held messages and reports land here. : items.map((i) => ( + {!items ? : items.length === 0 ? Nothing waiting. New uploads, held messages, reports and sign-in location flags land here. : items.map((i) => ( {i.photo ? ( setBig(i.photo!)} accessibilityRole="button" accessibilityLabel="View photo larger"> @@ -298,7 +300,7 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; ) : ( - + )} @@ -310,7 +312,21 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; {i.messageBody ? "{i.messageBody}" : null} {i.kind === 'profile' && i.profileText !== undefined ? decide(i.id, d, text)} rejectLabel={labels.profile[2]} approveLabel={labels.profile[1]} /> - : ( + : i.kind === 'risk' ? ( + <> + {/* what raised it (saved then), plus today's hints when they add something */} + {i.summary} + !i.summary.includes(f.text))} /> + {i.reasons.map((r) => )} + {i.status === 'pending' ? ( + + setOpenId(i.memberId)} /> + decide(i.id, 'approve')} /> + decide(i.id, 'reject')} /> + + ) : null} + + ) : ( <> {i.summary} @@ -329,6 +345,22 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; ))} setBig(null)} /> + setOpenId(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', +}; + +/** Hints from where a member signs in. They are for a person to judge; nothing is blocked automatically. */ +function RiskNotes({ flags }: { flags: RiskFlag[] }) { + if (!flags.length) return null; + return ( + + {flags.map((f) => {f.text})} + Hints, not proof: VPNs, travel and phone networks can show another country, and plenty of honest people write this way. Nothing is blocked automatically. IP country data by DB-IP (db-ip.com, CC BY 4.0); we keep only the country and network type, never the IP address. ); } @@ -473,8 +505,10 @@ function Members({ api, siteId }: { api: AdminApi; siteId: string }) { {m.tier !== 'free' ? : null} {m.status === 'suspended' ? : null} {m.reports ? 1 ? 's' : ''}`} tone="alert" /> : null} + {m.flags.map((f) => )} {m.city || 'No city yet'} · {m.photoCount} photos · joined {relTime(m.createdAt)} · active {relTime(m.lastActiveAt)} + {m.flags[0] ? {m.flags[0].text} : null} 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' }))} /> @@ -542,6 +576,13 @@ function MemberProfilePanel({ api, siteId, memberId, onClose }: { api: AdminApi; {p.cautions.length ? p.cautions.map((c) => {c}) : null} + {data.flags.length ? : null} + {data.network?.countries.length ? ( + + Signs in from: {data.network.countries.map((c) => `${c.name} (${c.count === 1 ? 'once' : `${c.count} times`}, last ${relTime(c.lastAt)})`).join(', ')} + {data.network.hosting ? ` · last VPN or hosting network: ${data.network.hosting.org}` : ''} + + ) : null} About me {p.about ? : Empty.} diff --git a/package-lock.json b/package-lock.json index 8e024f6..7ce14b7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,6 +23,7 @@ "@whatbox/core": "^0.1.0", "all-the-cities": "3.1.0", "jose": "^6.2.18", + "mmdb-lib": "^3.0.5", "mssql": "^12.8.3", "mysql2": "^3.24.6", "pg": "^8.23.1", @@ -9001,6 +9002,16 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/mmdb-lib": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/mmdb-lib/-/mmdb-lib-3.0.5.tgz", + "integrity": "sha512-fBhq5SQHKXwL4dPwF4/Xesw6Ai5nsPlft7RWQwBOm5fhfrQs0r1dR7FbLCaaKH9pkub2s4BKrHAeZUjq+KrX7g==", + "license": "MIT", + "engines": { + "node": ">=10", + "npm": ">=6" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", diff --git a/packages/core/src/demo-analytics.ts b/packages/core/src/demo-analytics.ts index 0c2db7a..885ef8b 100644 --- a/packages/core/src/demo-analytics.ts +++ b/packages/core/src/demo-analytics.ts @@ -2,6 +2,7 @@ import { addDays, utcDay } from './analytics'; import type { SiteRepo } from './repo'; import type { Site } from './types'; +import { riskFlags, riskReasons } from './network-risk'; function rng(seed: number) { let x = seed || 1; @@ -40,3 +41,17 @@ function refHost(u: string) { const h = new URL(u).hostname.replace(/^www\./, ''); return h.startsWith('google.') ? 'google' : h === 'bing.com' ? 'bing' : h === 'duckduckgo.com' ? 'duckduckgo' : h; } + +/** Preview only: one demo member who signs in from abroad, so the "Possible scammer" review can be seen. */ +export async function seedDemoRisk(repo: SiteRepo, now: Date, memberId: string | undefined) { + const m = memberId ? await repo.getMember(memberId) : null; + if (!m || !m.country) return; + const at = new Date(now.getTime() - 2 * 3600e3).toISOString(); + m.network = { countries: [{ code: m.country === 'NG' ? 'GH' : 'NG', count: 4, lastAt: at }], hosting: { org: 'M247 Europe SRL', lastAt: at } }; + m.about = `Am a God fearing and honest man, new to this. ${m.about}`.trim(); + const all = riskFlags(m), flags = all.filter((f) => f.review); + 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 }); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index faea7c8..5a77ba1 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 './network-risk'; diff --git a/packages/core/src/memory-platform.ts b/packages/core/src/memory-platform.ts index db4c1ad..0eccad5 100644 --- a/packages/core/src/memory-platform.ts +++ b/packages/core/src/memory-platform.ts @@ -2,10 +2,11 @@ import { DevKeyProvider, SiteCrypto } from './crypto'; import { MemoryControlRepo, MemorySiteRepo, type ControlSnapshot, type SiteSnapshot } from './memory-repo'; import type { Clock, IdTokenVerifier, Notifier, PaymentGateway } from './repo'; +import type { IpIntel } from './network-risk'; import { DEMO_MEMBER_EMAIL, seedAdmins, seedSite, seedSites } from './seed'; import { Platform } from './services'; import { LocalEventHub } from './events'; -import { seedDemoAnalytics } from './demo-analytics'; +import { seedDemoAnalytics, seedDemoRisk } from './demo-analytics'; export interface MemoryPlatformSnapshot { v: 1; control: ControlSnapshot; sites: Record } @@ -28,6 +29,7 @@ export async function createMemoryPlatform(opts: { payments?: Partial>; idTokens?: IdTokenVerifier; demoAnalytics?: boolean; // placeholder dashboard history (the preview turns it on) + ipIntel?: IpIntel; // tests only: stands in for the API's local IP database } = {}): Promise { const keys = new DevKeyProvider(opts.masterKey ?? 'preview-master-key'); const now = opts.clock?.now() ?? new Date(); @@ -46,7 +48,10 @@ export async function createMemoryPlatform(opts: { demoMemberHash: { emailHash: await crypto.lookupHash(DEMO_MEMBER_EMAIL), emailEnc: await crypto.encrypt(DEMO_MEMBER_EMAIL) }, }); const repo = new MemorySiteRepo(seed); - if (opts.demoAnalytics) { await seedDemoAnalytics(repo, site, now, seed.members.map((m) => m.id)); await repo.cleanup(now.toISOString()); } + if (opts.demoAnalytics) { + await seedDemoAnalytics(repo, site, now, seed.members.map((m) => m.id)); await repo.cleanup(now.toISOString()); + if (site.slug === 'afterh') await seedDemoRisk(repo, now, seed.members.find((m) => m.profileComplete && m.displayName && m.gender === 'man' && m.country)?.id); + } sites.set(site.id, repo); } } @@ -63,7 +68,7 @@ export async function createMemoryPlatform(opts: { return r; }, keys, notifier, clock: opts.clock, exposeDevCodes: opts.exposeDevCodes ?? true, onChange: opts.onChange, rateLimitScale: opts.rateLimitScale, idTokens: opts.idTokens, events: new LocalEventHub(), - allowSelfServeTier: opts.allowSelfServeTier ?? true, payments: opts.payments, + allowSelfServeTier: opts.allowSelfServeTier ?? true, payments: opts.payments, ipIntel: opts.ipIntel, }); return { diff --git a/packages/core/src/memory-repo.ts b/packages/core/src/memory-repo.ts index 1ff0e15..0aed3c7 100644 --- a/packages/core/src/memory-repo.ts +++ b/packages/core/src/memory-repo.ts @@ -1,6 +1,7 @@ // In-memory repositories. Used by tests and by the browser preview, where state is // snapshotted to localStorage. Each site gets its own MemorySiteRepo instance, mirroring // the one-database-per-site layout of production. +import { pruneNetwork } from './network-risk'; import type { AdminChallenge, AdminSession, ControlRepo, MemberQuery, MemberSession, SiteRepo } from './repo'; import type { UsageKind, AuditEntry, EventRsvp, SiteEvent, AdminUser, Block, Favorite, Pass, ContactOptIn, ContentPage, Like, Member, Message, ModerationItem, Photo, @@ -322,6 +323,7 @@ export class MemorySiteRepo implements SiteRepo { a.visitors = a.visitors.filter((x) => x.day >= keep); const stale = new Date(Date.parse(now) - 2 * 86400e3).toISOString(); d.subscriptions = (d.subscriptions ?? []).filter((s) => !(s.status === 'pending' && s.createdAt < stale)); + for (const m of d.members) if (m.network) { const n = pruneNetwork(m.network, new Date(now)); if (n) m.network = n; else delete m.network; } const lapsed: string[] = []; for (const s of d.subscriptions) { if (s.status === 'cancelled' && s.currentPeriodEnd && s.currentPeriodEnd < now) { s.status = 'expired'; s.updatedAt = now; lapsed.push(s.memberId); } diff --git a/packages/core/src/network-risk.ts b/packages/core/src/network-risk.ts new file mode 100644 index 0000000..72df25a --- /dev/null +++ b/packages/core/src/network-risk.ts @@ -0,0 +1,212 @@ +// Scam and fake-profile hints. This is the scoring engine: plain functions over a member's country, +// sign-in networks and profile text, with no database or platform code, so it can later run as its +// own metered service (a paid moderation add-on for third-party sites) behind the same riskFlags() shape. +// +// Risk hints from where a member signs in. At each sign-in the API looks the IP up in a local database +// (no member IP is ever sent to an outside service) and keeps only what it derives: the country and +// whether the network is Tor or a hosting provider. The IP itself is never stored. +// Flags are hints for a person to review in Owner Admin. Nothing here blocks or suspends anyone. +import { countryName } from './geo'; +import type { Member } from './types'; + +/** What a local IP database says about one address. */ +export interface NetworkInfo { + country?: string; // ISO 3166 two-letter code + asn?: number; + 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 +} + +export interface IpIntel { + lookup(ip: string): NetworkInfo | null | Promise; +} + +/** Kept on the member. Derived from sign-ins; never the IP. */ +export interface MemberNetwork { + /** Countries signed in from, most recent first, at most MAX_COUNTRIES. */ + countries: { code: string; count: number; lastAt: string }[]; + /** The last hosting or VPN network seen, if any. */ + hosting?: { org: string; lastAt: string }; + /** Last sign-in over Tor. */ + torAt?: string; +} + +export type RiskCode = 'country_mismatch' | 'tor' | 'hosting' | 'dropped_i' | 'spelling' | 'scam_phrases'; +export interface RiskFlag { code: RiskCode; text: string; /** true when it goes to the moderation queue */ review: boolean } + +const MAX_COUNTRIES = 5; +/** Sign-in history older than this is dropped, so the record doesn't become a travel log. */ +export const NETWORK_KEEP_DAYS = 180; +const DAY_MS = 86_400_000; + +/** Adds one sign-in to the member's network record. Returns the updated record (input is not changed). */ +export function noteSignIn(prev: MemberNetwork | undefined, info: NetworkInfo, now: Date): MemberNetwork { + const at = now.toISOString(); + const cutoff = now.getTime() - NETWORK_KEEP_DAYS * DAY_MS; + const keep = (iso?: string) => !!iso && Date.parse(iso) >= cutoff; + let countries = (prev?.countries ?? []).filter((c) => keep(c.lastAt)); + if (info.country && /^[A-Z]{2}$/.test(info.country)) { + const old = countries.find((c) => c.code === info.country); + countries = [{ code: info.country, count: (old?.count ?? 0) + 1, lastAt: at }, ...countries.filter((c) => c.code !== info.country)].slice(0, MAX_COUNTRIES); + } + const next: MemberNetwork = { countries }; + if (info.hosting && info.org) next.hosting = { org: info.org.slice(0, 80), lastAt: at }; + else if (keep(prev?.hosting?.lastAt)) next.hosting = prev!.hosting; + if (info.tor) next.torAt = at; + else if (keep(prev?.torAt)) next.torAt = prev!.torAt; + return next; +} + +/** Drops sign-in history older than NETWORK_KEEP_DAYS. Returns undefined when nothing is left. */ +export function pruneNetwork(n: MemberNetwork | undefined, now: Date): MemberNetwork | undefined { + if (!n) return undefined; + const cutoff = now.getTime() - NETWORK_KEEP_DAYS * DAY_MS; + const keep = (iso?: string) => !!iso && Date.parse(iso) >= cutoff; + const out: MemberNetwork = { countries: n.countries.filter((c) => keep(c.lastAt)) }; + if (keep(n.hosting?.lastAt)) out.hosting = n.hosting; + if (keep(n.torAt)) out.torAt = n.torAt; + return out.countries.length || out.hosting || out.torAt ? out : undefined; +} + +const name = (code: string) => countryName(code); +const list = (codes: string[]) => codes.length <= 1 ? codes.map(name).join('') : codes.slice(0, -1).map(name).join(', ') + ' and ' + name(codes[codes.length - 1]); + +/** + * The hints for one member, worst first. + * - country_mismatch: none of the countries they sign in from is the country on their profile. Goes to review. + * Signing in from the profile country even once (say, before a trip) is enough not to flag. + * - 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), ...textFlags(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; + return out; +} + +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 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)}.` }); + } + 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.` }); + return out; +} + +// ---------------- 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; + +/** British and Commonwealth spellings. Normal for most of the world, so only counted for members who say they're in the US. */ +const BRITISH = /\b(colours?|colourful|favourite|favour|honour|honourable|humour|behaviour|neighbour|labour|flavour|harbour|centre|theatre|metre|kilometre|travelled|travelling|cancelled|jewellery|cheque|realise|realised|recognise|organise|apologise|analyse|programme|mum|whilst|amongst|grey)\b/i; + +/** Wording that turns up again and again in romance-scam profiles. */ +const SCAM_PHRASES: [RegExp, string][] = [ + [/\bgod[\s-]?fearing\b/i, '"God fearing"'], + [/\bmy late (wife|husband)\b|\bwidow(er|ed)? with\b/i, 'widowed parent story'], + [/\b(oil\s?rig|offshore (engineer|platform)|peace\s?keeping|un mission|deployed|army general|military doctor|contractor (in|abroad)|ship captain)\b/i, 'working-abroad story'], + [/\bkindly\b/i, '"kindly"'], + [/\b(my dear|hello dear|hi dear|dearest)\b/i, '"dear" greeting'], + [/\b(whats\s?app|telegram|hangouts?|signal app|google chat|kik)\b/i, 'asks to move to another app'], + [/\b(honest|caring|loving|god|serious)[\s,]+(and\s+)?(caring|loving|honest|understanding|romantic)\s+(man|woman|lady|gentleman)\b/i, 'stock self-description'], + [/\bi am (a )?(new|newbie) (here|on this site)\b/i, '"new here" opener'], + [/\b(age|distance|colou?r|race) (is|does) not (a )?matter\b|\bage is just a number\b/i, '"age doesn\'t matter"'], +]; + +export function textFlags(about: string, country?: string): RiskFlag[] { + const text = about.trim(); + if (!text) return []; + const out: RiskFlag[] = []; + const d = text.match(DROPPED_I); + if (d) out.push({ code: 'dropped_i', review: false, text: `Writes "${d[0].trim().slice(0, 40)}…" with the "I" dropped, common with non-native writers.` }); + if ((country ?? '').toUpperCase() === 'US') { + const words = [...new Set([...text.matchAll(new RegExp(BRITISH.source, 'gi'))].map((x) => x[0].toLowerCase()))]; + if (words.length) out.push({ code: 'spelling', review: false, text: `Profile says United States but uses British spelling (${words.slice(0, 4).join(', ')}).` }); + } + const hits = SCAM_PHRASES.filter(([re]) => re.test(text)).map(([, label]) => label); + if (hits.length) out.push({ code: 'scam_phrases', review: false, text: `Wording common in scam profiles: ${hits.join(', ')}.` }); + return out; +} + +const REASON: Record = { + country_mismatch: 'country mismatch', tor: 'Tor', hosting: 'VPN or hosting', 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 { + 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(',') : ''; + return `${(m.country ?? '').toUpperCase()}|${f.map((x) => x.code).sort().join(',')}|${countries}`; +} + +// ---------------- Hosting networks ---------------- +// Autonomous systems that are datacenters, clouds or VPN providers rather than homes and phones. +// Not complete; the organisation-name test below catches many of the rest. +export const HOSTING_ASNS = new Set([ + 16509, 14618, 8987, // Amazon AWS + 8075, 8068, 8069, // Microsoft Azure + 396982, 19527, // Google Cloud + 31898, // Oracle Cloud + 45102, 37963, // Alibaba Cloud + 132203, 45090, // Tencent Cloud + 14061, // DigitalOcean + 63949, // Akamai Connected Cloud (Linode) + 20473, // Vultr (Choopa) + 16276, // OVH + 24940, 213230, // Hetzner + 51167, // Contabo + 60781, 28753, 30633, // Leaseweb + 9009, // M247 (many consumer VPNs) + 212238, // Datacamp / CDN77 (many consumer VPNs) + 136787, // TEFINCOM (NordVPN) + 207137, // PacketHub (NordVPN) + 147049, // PacketHub + 39351, // 31173 Services (Mullvad) + 62240, // Clouvider + 9002, // RETN + 174, // Cogent (mostly transit and hosting) + 46562, // Performive + 36352, // ColoCrossing / HostPapa + 53667, // FranTech / BuyVM + 8100, // QuadraNet + 35916, // MultaCom + 40065, // Cnservers + 202425, // IP Volume + 57523, // Chang Way + 44477, // Stark Industries + 210644, // Aeza + 401115, // EKABI + 23470, // ReliableSite + 7979, // Servers.com + 12876, // Scaleway + 197540, // netcup + 42708, // GleSYS + 61317, // Digital Energy (Heficed) + 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; + +/** True when the network looks like a datacenter, cloud or VPN provider. */ +export function isHostingNetwork(asn: number | undefined, org: string | undefined): boolean { + if (asn && HOSTING_ASNS.has(asn)) return true; + return !!org && HOSTING_ORG.test(org); +} diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts index 08f7063..084db00 100644 --- a/packages/core/src/services.ts +++ b/packages/core/src/services.ts @@ -2,7 +2,8 @@ // so the rules a member hits are the same everywhere. import { LocalEventHub } from './events'; import { DevKeyProvider, hmacHex, type KeyProvider, randomCode, randomId, SiteCrypto } from './crypto'; -import { builtinGeo, unitsForCountry } from './geo'; +import { builtinGeo, countryName, unitsForCountry } from './geo'; +import { type IpIntel, noteSignIn, riskFlags, riskKey, riskReasons } from './network-risk'; import { buildSiteDashboard, cleanHitPath, combineDashboards, DASHBOARD_DAYS, emptySiteDashboard, isBotAgent, publicGoogleTags, referrerHost, utcDay, addDays, validateGoogleTags, } from './analytics'; @@ -36,6 +37,7 @@ export interface PlatformDeps { exposeDevCodes?: boolean; // return codes to the client (dev and preview only) rateLimitScale?: number; // multiplies every rate limit; >1 only for local dev and test runs geo?: GeoProvider; // worldwide places; the preview uses a small built-in list + ipIntel?: IpIntel; // local IP-to-country database for sign-in risk hints; absent in the preview onChange?: () => void; // preview persistence hook } @@ -192,7 +194,7 @@ export class Platform { return { challengeId: id, sentTo: maskTarget(channel, target), devCode: this.deps.exposeDevCodes ? code : undefined }; } - async verifyCode(site: Site, challengeId: string, code: string) { + async verifyCode(site: Site, challengeId: string, code: string, meta: { ip?: string } = {}) { const repo = await this.repo(site); const crypto = this.crypto(site); const c = await repo.getChallenge(challengeId); @@ -217,9 +219,40 @@ export class Platform { else { member.phoneHash = c.targetHash; member.phoneEnc = c.targetEnc; } await repo.saveMember(member); } + if (member.status !== 'suspended') await this.noteNetwork(site, repo, member, meta.ip); return this.startSession(site, member, isNew); } + /** Looks the sign-in IP up in the local database and keeps only the country and network type. + * Never throws: a missing or broken database must not stop anyone signing in. */ + private async noteNetwork(site: Site, repo: SiteRepo, member: Member, ip?: string) { + if (!ip || !this.deps.ipIntel) return; + try { + const info = await this.deps.ipIntel.lookup(ip); + if (!info || (!info.country && !info.hosting && !info.tor)) return; + member.network = noteSignIn(member.network, info, this.now()); + await this.checkRisk(site, repo, member); + await repo.saveMember(member); + } catch (e) { console.error('[network]', site.id, (e as Error).message); } + } + + /** Puts a member in the moderation queue when their review flags are new. Saves the item, not the member. */ + private async checkRisk(site: Site, repo: SiteRepo, member: Member) { + const key = riskKey(member); + if (!key || key === member.risk?.clearedKey) return; + const all = riskFlags(member), flags = all.filter((f) => f.review); + const open = member.risk?.openItemId ? await repo.getModeration(member.risk.openItemId) : null; + const reasons = riskReasons(all); + const summary = flags.map((f) => f.text).join(' '); + if (open && open.status === 'pending') { + if (open.summary !== summary) await repo.saveModeration({ ...open, summary, reasons }); + return; + } + const id = randomId('mod_'); + await repo.saveModeration({ id, kind: 'risk', refId: member.id, memberId: member.id, summary, reasons, status: 'pending', createdAt: this.iso() }); + member.risk = { ...member.risk, openItemId: id }; + } + private newMember(): Member { const now = this.iso(); return { @@ -272,6 +305,7 @@ export class Platform { if (!member) { member = this.newMember(); isNew = true; } // Apple "hide my email" without a relay address member.identityHashes = [...new Set([...(member.identityHashes ?? []), idHash])]; await repo.saveMember(member); + if (member.status !== 'suspended') await this.noteNetwork(site, repo, member, meta.ip); return this.startSession(site, member, isNew); } @@ -392,7 +426,8 @@ export class Platform { // ---------------- My profile and photos ---------------- async myProfile(ctx: MemberCtx): Promise { - const { emailHash, emailEnc, phoneHash, phoneEnc, ...rest } = ctx.me; + // network and risk are for admins only; showing them would tell a scammer what gave them away + const { emailHash, emailEnc, phoneHash, phoneEnc, network, risk, ...rest } = ctx.me; const crypto = this.crypto(ctx.site); const contactRaw = emailEnc ? await crypto.decrypt(emailEnc) : phoneEnc ? await crypto.decrypt(phoneEnc) : ''; const photos = await ctx.repo.listPhotos(ctx.me.id); @@ -477,6 +512,8 @@ export class Platform { const missing = ctx.site.fields.filter((f) => f.required && (m.fields[f.key] === undefined || m.fields[f.key] === '')); if (m.displayName && m.city && !missing.length) 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); await ctx.repo.saveMember(m); this.changed(); return this.myProfile(ctx); @@ -1421,6 +1458,7 @@ 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) : []; } out.push(v); } return out; @@ -1452,6 +1490,13 @@ export class Platform { } else if (item.kind === 'profile' && decision === 'reject') { const m = await repo.getMember(item.memberId); if (m) await repo.saveMember({ ...m, about: '' }); + } else if (item.kind === 'risk') { + // approve = looks fine: these flags stay quiet until something new shows up. reject = suspend. + 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' ? { status: 'suspended' as const } : {}) }); + } } await repo.saveModeration({ ...item, status, decidedAt: this.iso(), decidedBy: admin.email }); await this.audit(admin, `moderation.${decision}`, site.id, item.memberId, item.kind); @@ -1514,7 +1559,10 @@ 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 network = m.network ? { + countries: m.network.countries.map((c) => ({ ...c, name: countryName(c.code) })), hosting: m.network.hosting, torAt: m.network.torAt, + } : undefined; + return { profile, photos, status: m.status, profileComplete: m.profileComplete, createdAt: m.createdAt, imported: !!m.imported, flags: riskFlags(m), network, country: m.country }; } async adminMembers(admin: AdminUser, siteId: string, opts: { search?: string; page?: number }) { @@ -1528,7 +1576,7 @@ export class Platform { out.push({ id: m.id, displayName: m.displayName || '(unfinished signup)', age: ageFromBirthYear(m.birthYear, this.now()), city: m.city, status: m.status, tier: this.tierOf(m), createdAt: m.createdAt, lastActiveAt: m.lastActiveAt, - photoCount: photos.filter((p) => p.memberId === m.id).length, reports: await repo.countReports(m.id), + photoCount: photos.filter((p) => p.memberId === m.id).length, reports: await repo.countReports(m.id), flags: riskFlags(m), }); } return { total, page, rows: out }; diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 0f31775..6e0b2ad 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -1,6 +1,7 @@ // Domain types shared by the API, the member app and the public site. // Control-plane records (sites, admins) live in the shared control database. // Everything under "Per-site records" lives in that site's own database. +import type { MemberNetwork, RiskFlag } from './network-risk'; export type SiteMode = 'standard' | 'sensitive' | 'adult'; export type ClientPlatform = 'web' | 'ios' | 'android'; @@ -219,6 +220,10 @@ export interface Member { identityHashes?: string[]; // HMACs of "apple:" / "google:" for social sign-in /** Set on members brought over from an old site: which source systems and when. */ imported?: { sources: string[]; at: string }; + /** 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 }; createdAt: string; lastActiveAt: string; } @@ -277,7 +282,8 @@ export interface Report { at: string; } -export type ModerationKind = 'photo' | 'message' | 'report' | 'profile'; +/** risk: where they sign in from doesn't fit their profile (see network-risk.ts). */ +export type ModerationKind = 'photo' | 'message' | 'report' | 'profile' | 'risk'; export interface ModerationItem { id: string; kind: ModerationKind; @@ -434,7 +440,7 @@ export interface MemberProfile extends MemberCard { export interface CheckoutStart { checkoutUrl: string; subscriptionId: string } export interface MyProfile { - member: Omit & { contact: string; unitsResolved: Units }; + member: Omit & { contact: string; unitsResolved: Units }; perms: TierPerms; // what I can do right now (full access while the paywall is off) paywallEnabled: boolean; subscription?: { tier: 'paid' | 'vip'; status: SubscriptionStatus; currentPeriodEnd?: string; provider: string }; @@ -634,6 +640,8 @@ export interface AdminMemberRow { lastActiveAt: string; photoCount: number; reports: number; + /** Hints from where they sign in (country mismatch, Tor, VPN or hosting). For review, never automatic. */ + flags: RiskFlag[]; } export interface AdminMemberProfile { @@ -645,6 +653,11 @@ export interface AdminMemberProfile { profileComplete: boolean; createdAt: string; imported: boolean; + flags: RiskFlag[]; + /** Where they sign in from, by country and network type (derived; the IP is never kept). */ + network?: { countries: { code: string; name: string; count: number; lastAt: string }[]; hosting?: { org: string; lastAt: string }; torAt?: string }; + /** The profile country, for comparing with the sign-in countries. */ + country?: string; } export interface ModerationView extends ModerationItem { @@ -655,6 +668,8 @@ export interface ModerationView extends ModerationItem { profileText?: string; /** Profile items: where the contact check finds contact details in profileText today. */ contactMatches?: { start: number; end: number; kind: 'email' | 'url' | 'phone' | 'handle' }[]; + /** Risk items: today's hints for the member (they can change after the item was raised). */ + flags?: RiskFlag[]; } /** approve/reject as before; redact removes only the contact details; edit saves the admin's corrected text. */ diff --git a/packages/core/test/network-risk.test.ts b/packages/core/test/network-risk.test.ts new file mode 100644 index 0000000..eb74d29 --- /dev/null +++ b/packages/core/test/network-risk.test.ts @@ -0,0 +1,143 @@ +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, +} from '../src/index'; + +const NETS: Record = { + '73.0.0.1': { country: 'US', asn: 7922, org: 'Comcast Cable Communications, LLC' }, + '102.89.0.1': { country: 'NG', asn: 29465, org: 'MTN NIGERIA Communication limited' }, + '41.58.0.1': { country: 'GH', asn: 30986, org: 'Scancom' }, + '193.32.249.1': { country: 'NL', asn: 39351, org: '31173 Services AB', hosting: true }, + '185.220.101.1': { country: 'DE', asn: 60729, org: 'Stiftung Erneuerbare Freiheit', tor: true }, +}; +const intel: IpIntel = { lookup: (ip) => NETS[ip] ?? null }; + +async function setup() { + const mp = await createMemoryPlatform({ ipIntel: intel }); + const site = (await mp.control.getSite('site_afterh'))!; + const signIn = async (email: string, ip: string) => { + const s = await mp.platform.startVerification(site, 'email', email, { ip }); + return mp.platform.verifyCode(site, s.challengeId, s.devCode!, { ip }); + }; + const admin = createLocalAdminApi(mp.platform); + const st = await admin.start(DEMO_OWNER_EMAIL); + admin.setToken((await admin.verify(st.challengeId, st.devCode!)).token); + return { mp, site, signIn, admin, repo: mp.sites.get('site_afterh')! }; +} + +test('a US profile signing in from Nigeria is flagged for review; the IP is not kept', async () => { + const { mp, signIn, admin, repo } = await setup(); + const { token } = await signIn('scam.test@example.com', '102.89.0.1'); + const api = createLocalMemberApi(mp.platform, 'afterh', 'web'); + api.setToken(token); + // no flag before they say where they live + assert.equal((await admin.moderation('site_afterh', 'pending')).filter((i) => i.kind === 'risk').length, 0); + await api.updateMe({ displayName: 'Brenda', birthYear: 1985, gender: 'woman', seeking: ['man'], location: { country: 'US', postal: '80202' }, fields: { hsv_status: ['HSV-1'] } }); + 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.equal(items[0].flags?.[0].code, 'country_mismatch'); + + const me = (await api.me()).member as Record; + assert.equal(me.network, undefined, 'members never see their own risk data'); + assert.equal(me.risk, undefined); + const stored = JSON.stringify(await repo.getMember(items[0].memberId)); + assert.ok(!stored.includes('102.89'), 'the IP itself is never stored'); + + const rows = (await admin.members('site_afterh', { search: 'Brenda' })).rows; + assert.equal(rows[0].flags[0].code, 'country_mismatch'); + const prof = await admin.memberProfile('site_afterh', items[0].memberId); + assert.equal(prof.network?.countries[0].name, 'Nigeria'); + assert.equal(prof.country, 'US'); + + // signing in again from the same place doesn't add a second item + await signIn('scam.test@example.com', '102.89.0.1'); + assert.equal((await admin.moderation('site_afterh', 'pending')).filter((i) => i.kind === 'risk').length, 1); + + // "Looks fine" quiets it until something new shows up + await admin.decide('site_afterh', items[0].id, 'approve'); + await signIn('scam.test@example.com', '102.89.0.1'); + assert.equal((await admin.moderation('site_afterh', 'pending')).filter((i) => i.kind === 'risk').length, 0); + await signIn('scam.test@example.com', '41.58.0.1'); + const again = (await admin.moderation('site_afterh', 'pending')).filter((i) => i.kind === 'risk'); + assert.equal(again.length, 1); + assert.match(again[0].summary, /Ghana and Nigeria/); + + // the other button suspends + await admin.decide('site_afterh', again[0].id, 'reject'); + assert.equal((await repo.getMember(again[0].memberId))!.status, 'suspended'); +}); + +test('a member who has signed in from home is not flagged when travelling; Tor is', async () => { + const { mp, signIn, admin } = await setup(); + const { token } = await signIn('traveller@example.com', '73.0.0.1'); + const api = createLocalMemberApi(mp.platform, 'afterh', 'web'); + api.setToken(token); + await api.updateMe({ displayName: 'Sam', birthYear: 1980, gender: 'man', seeking: ['woman'], location: { country: 'US', postal: '80202' }, fields: { hsv_status: ['HSV-1'] } }); + await signIn('traveller@example.com', '102.89.0.1'); + assert.equal((await admin.moderation('site_afterh', 'pending')).filter((i) => i.kind === 'risk').length, 0); + await signIn('traveller@example.com', '185.220.101.1'); + const items = (await admin.moderation('site_afterh', 'pending')).filter((i) => i.kind === 'risk'); + assert.equal(items.length, 1); + assert.deepEqual(items[0].reasons, ['Tor']); +}); + +test('a VPN alone is a note on the member, not a queue item; no database means no flags', async () => { + const { mp, signIn } = await setup(); + await signIn('vpn.user@example.com', '193.32.249.1'); + const all = await mp.sites.get('site_afterh')!.listAllMembers(200, 0); + const lee = all.rows.find((r) => r.network?.hosting)!; + assert.ok(lee); + lee.country = 'NL'; + assert.deepEqual(riskFlags(lee).map((f) => [f.code, f.review]), [['hosting', false]]); + assert.equal(riskKey(lee), ''); + + const plain = await createMemoryPlatform(); + const site = (await plain.control.getSite('site_afterh'))!; + const s = await plain.platform.startVerification(site, 'email', 'x@example.com', { ip: '102.89.0.1' }); + await plain.platform.verifyCode(site, s.challengeId, s.devCode!, { ip: '102.89.0.1' }); + const rows = (await plain.sites.get('site_afterh')!.listAllMembers(500, 0)).rows; + assert.ok(rows.every((r) => !r.network)); +}); + +test('sign-in history is capped and old entries are dropped', () => { + const t0 = new Date('2026-01-01T00:00:00Z'); + let n = noteSignIn(undefined, { country: 'US' }, t0); + for (const c of ['CA', 'MX', 'GB', 'FR', 'DE']) n = noteSignIn(n, { country: c }, t0); + assert.equal(n.countries.length, 5); + assert.equal(n.countries[0].code, 'DE'); + assert.ok(!n.countries.some((c) => c.code === 'US')); + n = noteSignIn(n, { country: 'DE', hosting: true, org: 'M247 Europe SRL' }, t0); + assert.equal(n.countries[0].count, 2); + assert.equal(n.hosting?.org, 'M247 Europe SRL'); + assert.equal(pruneNetwork(n, new Date('2026-12-01T00:00:00Z')), undefined); + assert.ok(pruneNetwork(n, new Date('2026-03-01T00:00:00Z'))); +}); + +test('hosting networks are recognised by number or name', () => { + assert.equal(isHostingNetwork(14061, 'DigitalOcean, LLC'), true); + assert.equal(isHostingNetwork(9009, 'M247 Europe SRL'), true); + assert.equal(isHostingNetwork(1, 'Some Hosting Ltd'), true); + assert.equal(isHostingNetwork(7922, 'Comcast Cable Communications, LLC'), false); + assert.equal(isHostingNetwork(29465, 'MTN NIGERIA Communication limited'), false); + assert.equal(isHostingNetwork(13335, 'Cloudflare, Inc.'), false); +}); + +test('writing hints: dropped "I", British spelling only for US profiles, scam wording; scored together', () => { + const t = (about: string, country = 'US') => riskFlags({ country, about }).map((f) => [f.code, f.review]); + assert.deepEqual(t('Am a simple and honest man looking for love.'), [['dropped_i', false]]); + assert.deepEqual(t('Am I the only one who likes hiking?'), []); + assert.deepEqual(t('I love the colour blue and my favourite food is pie.', 'GB'), []); + assert.deepEqual(t('I love the colour blue and my favourite food is pie.'), [['spelling', false]]); + // two hints together go to review + assert.deepEqual(t('Hello dear. Am a God fearing widower. My favourite colour is blue.'), + [['dropped_i', true], ['spelling', true], ['scam_phrases', true]]); + assert.deepEqual(t('Just a normal guy who likes dogs and tacos.'), []); + // a sign-in mismatch makes a single writing hint reviewable too + const m = { country: 'US', about: 'Am new here', network: { countries: [{ code: 'NG', count: 3, lastAt: '2026-11-01T00:00:00Z' }] } }; + assert.ok(riskFlags(m).every((f) => f.review)); + assert.notEqual(riskKey(m), ''); +});