Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,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);
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/import/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
23 changes: 12 additions & 11 deletions apps/api/src/import/legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, { ip: unknown; at?: string | null; count?: number }[]>();
// 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)');

Expand Down Expand Up @@ -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 {
Expand Down
47 changes: 29 additions & 18 deletions apps/api/src/import/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -330,36 +331,46 @@ export async function riskCheckImported(bundles: Bundle[], d: Pick<LoadDeps, 'si
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: {} };
const at = d.now.toISOString();
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 (!g.m.network?.countries.length) bump(report.members, 'no recent sign-in to place (name and 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 risk = { ...m.risk, sharedSignup: g.m.sharedSignup || undefined };
const view = { country: m.country, network: mergeNetworks(g.m.network, m.network), about: m.about, displayName: m.displayName, imported: m.imported, risk };
const all = riskFlags(view), flags = all.filter((f) => 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;
}
Expand Down
55 changes: 55 additions & 0 deletions apps/api/src/import/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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<string, { keys: Set<string>; first: string; last: string }>();
for (const r of rows) {
const at = r.at ?? '';
const cur = byIp.get(r.ip) ?? { keys: new Set<string>(), 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<string>();
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<string, { ip: string; at?: string | null; count?: number }[]>();
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<string, MemberNetwork>();
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<string, { key: string; t: number }[]>();
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<string, number>();
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 };
}
12 changes: 8 additions & 4 deletions apps/api/src/import/skadate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)');

Expand Down Expand Up @@ -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 {
Expand Down
6 changes: 4 additions & 2 deletions apps/api/src/ipintel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
Loading
Loading