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
11 changes: 8 additions & 3 deletions .github/workflows/import.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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"
Expand Down
1 change: 1 addition & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
32 changes: 22 additions & 10 deletions apps/api/scripts/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir> [--bundle <dir>] [--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:<prefix> reads bundles from the private
// "imports" container, and --report-blob <name> writes the counts back there for the workflow summary.
//
Expand All @@ -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[]) {
Expand Down Expand Up @@ -87,7 +94,7 @@ async function argsFromBlob(): Promise<string[]> {
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);
}

Expand All @@ -97,20 +104,26 @@ async function argsFromBlob(): Promise<string[]> {
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;
}
Expand All @@ -130,7 +143,7 @@ async function argsFromBlob(): Promise<string[]> {
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; }
Expand All @@ -141,14 +154,13 @@ async function argsFromBlob(): Promise<string[]> {
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
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
5 changes: 5 additions & 0 deletions apps/api/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
5 changes: 4 additions & 1 deletion apps/api/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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<string, PgSiteRepo>();
const photos = createPhotoStore();
Expand Down Expand Up @@ -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 };
}
3 changes: 3 additions & 0 deletions apps/api/src/import/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 =
Expand Down
25 changes: 22 additions & 3 deletions apps/api/src/import/legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 <T = any>(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<string, Map<number, string>>();
for (const a of await q(`SELECT u_username, pq_id, pa_value FROM ProfileAnswers`)) {
Expand Down Expand Up @@ -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<string, { ip: unknown; at?: string | null; count?: number }[]>();
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<number, number>((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`);
Expand Down
Loading
Loading