From 0e604a3440e93d61c7898be8774566994237d629 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:28:04 +0000 Subject: [PATCH] Keep DateALittle and HFriends on-niche: default Browse to the niche, dwarfism type and disability categories, account review flags - DateALittle: Stature adds "Short stature"; new single-choice "Type of dwarfism" (old site's list, tidied). HFriends: broad disability categories (multi, no diagnosis) incl. "No disability", plus optional "More about my disability" text. migrate upgrades existing sites and keeps admin-added options. - Browse and Discover show members inside the niche by default; a Browse checkbox ("Include average-height members" / "Include members without a disability") includes everyone and is remembered. - Account review flags in Owner Admin Moderation (kind "member"): stated stature vs. height and gender, dwarfism type with "average height", "no disability" plus disabilities, ticking almost every box, couple-looking-for-a-third and fetish/gawker wording in About me, free text and messages. Review only: Looks fine / Suspend account / See profile. "Looks fine" sticks for the same evidence. - "Check all members" button runs the checks over existing members; the importer flags on load and now carries the exact dwarfism type, short stature and "No disability". - Heights down to 2'0" / 60 cm (DateALittle members under 3 feet). - Community guidelines page on both sites; FAQ lines on who Browse shows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015x8UvR6rK7ZuwNt3jeCZRC --- apps/api/src/app.ts | 3 + apps/api/src/import/legacy.ts | 2 +- apps/api/src/import/load.ts | 10 +- apps/api/src/import/map.ts | 58 +++++-- apps/api/test/import.test.ts | 12 +- apps/member/src/app/(app)/browse.tsx | 12 +- apps/member/src/app/admin/index.tsx | 41 ++++- apps/member/src/ui/FieldsEditor.tsx | 12 +- infra/import-members.md | 9 +- packages/core/src/api.ts | 2 + packages/core/src/http-client.ts | 1 + packages/core/src/index.ts | 1 + packages/core/src/niche.ts | 238 +++++++++++++++++++++++++++ packages/core/src/seed.ts | 23 ++- packages/core/src/services.ts | 70 +++++++- packages/core/src/starter-content.ts | 29 +++- packages/core/src/types.ts | 28 +++- packages/core/test/niche.test.ts | 175 ++++++++++++++++++++ 18 files changed, 682 insertions(+), 44 deletions(-) create mode 100644 packages/core/src/niche.ts create mode 100644 packages/core/test/niche.test.ts diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 738bd6c..977b7e1 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -223,6 +223,9 @@ export class AdminController { @Post('sites/:site/moderation-recheck') async recheck(@Headers('authorization') a: string, @Param('site') s: string) { return this.p.adminRecheckModeration(await this.admin(a), s); } + @Post('sites/:site/niche-checks') async nicheChecks(@Headers('authorization') a: string, @Param('site') s: string) { + return this.p.adminRunNicheChecks(await this.admin(a), s); + } @Get('sites/:site/members') async members(@Headers('authorization') a: string, @Param('site') s: string, @Query('search') q?: string, @Query('page') page?: string) { return this.p.adminMembers(await this.admin(a), s, { search: q || undefined, page: Number(page) || 1 }); } diff --git a/apps/api/src/import/legacy.ts b/apps/api/src/import/legacy.ts index d35ac50..32b91ee 100644 --- a/apps/api/src/import/legacy.ts +++ b/apps/api/src/import/legacy.ts @@ -56,7 +56,7 @@ export async function extractLegacy(site: LegacySite, connectionString: string, const set = (k: string, v: string | string[] | number | undefined) => { if (v !== undefined) fields[k] = v; }; if (site === 'afterh') set('hsv_status', legacyStatus(a.get(Q.q20))); if (site === 'hfriends') set('accessibility', legacyAccessibility(a.get(Q.q20), a.get(Q.q21))); - if (site === 'datealittle') set('stature', legacyStature(a.get(Q.q20))); + if (site === 'datealittle') { const st = legacyStature(a.get(Q.q20)); set('stature', st.stature); set('dwarfism_type', st.type); } set('relationship_goal', legacyGoal(a.get(Q.lookingFor))); set('height', legacyHeight(a.get(Q.height))); set('kids', legacyKids(a.get(Q.haveKids), a.get(Q.wantKids))); diff --git a/apps/api/src/import/load.ts b/apps/api/src/import/load.ts index 601bb3c..bf5fb52 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, flagMember, type Gender, memberFlags, type NicheFlag, 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'; @@ -120,6 +120,8 @@ export interface LoadReport { photos: Record; relations: Record; moderation: number; + /** Niche review flags by reason (DateALittle, HFriends). */ + niche: Record; } const short = (s: string) => createHash('sha256').update(s).digest('hex').slice(0, 24); @@ -132,10 +134,11 @@ export async function loadBundles(bundles: Bundle[], d: LoadDeps): Promise ({ source: b.info.source, members: b.members.length })), - members: {}, photos: {}, relations: {}, moderation: 0, + members: {}, photos: {}, relations: {}, moderation: 0, niche: {}, }; const idByKey = new Map(); const moderation: ModerationItem[] = []; + const niche: { memberId: string; f: NicheFlag }[] = []; const flagItem = (memberId: string, refId: string, kind: ModerationItem['kind'], summary: string, reason: string, createdAt = at) => moderation.push({ id: 'mod_imp_' + short(`${kind}:${refId}:${reason}`), kind, refId, memberId, summary, reasons: [reason], status: 'pending', createdAt }); @@ -202,6 +205,8 @@ export async function loadBundles(bundles: Bundle[], d: LoadDeps): Promise ['q20', x] as const), ...(disorder ?? '').split(':').map((x) => ['q21', x] as const)]; + for (const [q, raw] of parts) { const s = raw.trim().toLowerCase(); - if (!s || s === 'none' || s === 'no disability') continue; - if (/paraplegic|quadriplegic|spinal|spina bifida/.test(s)) out.push('Wheelchair user'); - else if (/mobility|physically|amputee|hemiplegic|polio|muscular dystrophy|arthrogryposis|brittle bone|osteogenesis|cerebral palsy|charcot/.test(s)) out.push('Uses a mobility aid'); + if (!s) continue; + // "None" under Type of Disorder only means no disorder; "No Disability" is the real "none" + if (s === 'none' || s === 'no disability') { if (q === 'q20') none = true; continue; } + if (/paraplegic|quadriplegic|hemiplegic|spinal|spina bifida/.test(s)) out.push('Wheelchair user'); + else if (/mobility|polio|muscular dystrophy|arthrogryposis|charcot|cerebral palsy/.test(s)) out.push('Uses a mobility aid'); + else if (/amputee/.test(s)) out.push('Limb difference or amputee'); + else if (/physically|brittle bone|osteogenesis/.test(s)) out.push('Other physical disability'); else if (/hearing/.test(s)) out.push('Deaf or hard of hearing'); else if (/vision/.test(s)) out.push('Blind or low vision'); - else if (/learning|asperger/.test(s)) out.push('Neurodivergent'); - else if (/speech|other/.test(s)) continue; // no matching option; the member can add it after signing in + else if (/speech/.test(s)) out.push('Speech or communication'); + else if (/learning/.test(s)) out.push('Learning or intellectual disability'); + else if (/asperger/.test(s)) out.push('Neurodivergent'); + else if (/bi ?polar|depression|anxiety|schizophrenia|personality/.test(s)) out.push('Mental health'); + else if (/^other$/.test(s)) out.push('Other'); else out.push('Chronic illness'); } + if (none) out.push('No disability'); return out.length ? uniq(out) : undefined; } -/** DateALittle "Dwarfism Type" (q20) to "Stature". The exact type isn't carried over (no matching field yet). */ -export function legacyStature(answer: string | undefined): string | undefined { +/** DateALittle "Dwarfism Type" (q20, one answer) to "Stature" and "Type of dwarfism". */ +export function legacyStature(answer: string | undefined): { stature?: string; type?: string } { const s = (answer ?? '').trim(); - if (!s) return undefined; - return /^none$/i.test(s) ? 'Average height' : 'Little person'; + if (!s) return {}; + if (/^none$/i.test(s)) return { stature: 'Average height' }; + if (/^short stature$/i.test(s)) return { stature: 'Short stature', type: 'Not sure / no diagnosis' }; + return { stature: 'Little person', type: legacyDwarfismType(s) }; +} + +/** Old DateALittle type names to the new list (rare or lethal types become "Another type"). */ +export function legacyDwarfismType(s: string): string { + const t = s.toLowerCase(); + const rules: [RegExp, string][] = [ + [/^hypochondroplasia/, 'Hypochondroplasia'], [/^pseudoachondroplasia/, 'Pseudoachondroplasia'], + [/^achondroplasia|saddan/, 'Achondroplasia'], [/diastrophic/, 'Diastrophic dysplasia'], + [/corner fracture|\(smd|kozlowski/, 'Spondylometaphyseal dysplasia (SMD)'], + [/strudwick|spondyloepimetaphyseal dysplasias$/, 'Spondyloepimetaphyseal dysplasia (SEMD)'], + [/\(sed|sedc|sedt|spondyloepimetaphyseal/, 'Spondyloepiphyseal dysplasia (SED)'], + [/multiple epiphyseal/, 'Multiple epiphyseal dysplasia (MED)'], [/^metaphyseal/, 'Metaphyseal chondrodysplasia'], + [/acromesomelic/, 'Acromesomelic dysplasia'], [/^mesomelic/, 'Mesomelic dysplasia'], [/campomelic/, 'Campomelic dysplasia'], + [/chondrodysplasia punctata|conradi/, 'Chondrodysplasia punctata'], [/cleidocranial/, 'Cleidocranial dysplasia'], + [/ellis van creveld/, 'Ellis-van Creveld syndrome'], [/kniest/, 'Kniest dysplasia'], [/larsen/, 'Larsen syndrome'], + [/weill/, 'Leri-Weill dyschondrosteosis'], [/metatropic/, 'Metatropic dysplasia'], [/osteogenesis imperfecta/, 'Osteogenesis imperfecta (OI)'], + [/morquio/, 'Morquio syndrome (MPS IV)'], [/mps|mucopolysacchar|hurler|hunter/, 'Other mucopolysaccharidosis (MPS)'], + [/primordial|seckel/, 'Primordial dwarfism (MOPD, Seckel)'], [/russell-silver/, 'Russell-Silver syndrome'], [/turner/, 'Turner syndrome'], + [/growth hormone/, 'Growth hormone deficiency'], [/laron/, 'Laron syndrome'], + [/pituitary|hypopituitary|hypothyroid|precocious/, 'Pituitary or hormonal'], [/hypophosphat|rickets/, 'Hypophosphatemia or rickets'], + ]; + return rules.find(([re]) => re.test(t))?.[1] ?? 'Another type'; } diff --git a/apps/api/test/import.test.ts b/apps/api/test/import.test.ts index 92884db..a928e43 100644 --- a/apps/api/test/import.test.ts +++ b/apps/api/test/import.test.ts @@ -30,9 +30,15 @@ test('profile answers', () => { assert.equal(legacyKids('Yes - but not at home', 'Yes'), 'Have kids, want more'); assert.deepEqual(skadateInterests(1 | 2048 | 1048576), ['Reading', 'Travel']); assert.deepEqual(legacyAccessibility('Paraplegic:Hearing Impaired', 'Multiple Sclerosis'), ['Wheelchair user', 'Deaf or hard of hearing', 'Chronic illness']); - assert.equal(legacyAccessibility('No Disability', 'None'), undefined); - assert.equal(legacyStature('Achondroplasia'), 'Little person'); - assert.equal(legacyStature('None'), 'Average height'); + assert.deepEqual(legacyAccessibility('No Disability', 'None'), ['No disability']); + assert.deepEqual(legacyAccessibility('Hearing Impaired', 'None'), ['Deaf or hard of hearing']); + assert.deepEqual(legacyAccessibility('Amputee:Speech Impaired:No Disability', 'Depression / Anxiety'), ['Limb difference or amputee', 'Speech or communication', 'Mental health', 'No disability']); + assert.deepEqual(legacyStature('Achondroplasia'), { stature: 'Little person', type: 'Achondroplasia' }); + assert.deepEqual(legacyStature('Short Stature'), { stature: 'Short stature', type: 'Not sure / no diagnosis' }); + assert.deepEqual(legacyStature('None'), { stature: 'Average height' }); + assert.equal(legacyStature('Spondyloepimetaphyseal Dysplasia Congenita (SEDC)').type, 'Spondyloepiphyseal dysplasia (SED)'); + assert.equal(legacyStature('Hurler-Scheie Syndrome (MPS I)').type, 'Other mucopolysaccharidosis (MPS)'); + assert.equal(legacyStature('Thanatophoric Dysplasia').type, 'Another type'); assert.deepEqual(skadateGenders(1 | 4), ['man', 'couple']); assert.deepEqual(seekingFor('man', ['couple']), ['woman']); assert.equal(countryCode('United States'), 'US'); diff --git a/apps/member/src/app/(app)/browse.tsx b/apps/member/src/app/(app)/browse.tsx index c5f9b53..3b9d042 100644 --- a/apps/member/src/app/(app)/browse.tsx +++ b/apps/member/src/app/(app)/browse.tsx @@ -13,13 +13,13 @@ const SORTS: { label: string; value: NonNullable }[] = [ ]; export default function Browse() { - const { api, me, site } = useSession(); + const { api, me, site, refreshMe } = useSession(); const t = useTheme(); const wide = useWide(980); const { height } = useWindowDimensions(); const units = me!.member.unitsResolved; const defaults = useCallback((): SearchFilters => ({ - seeking: me!.member.seeking, ageMin: me!.member.ageMin, ageMax: me!.member.ageMax, withinMiles: me!.member.maxMiles === undefined ? 50 : me!.member.maxMiles, withPhoto: true, onlineNow: false, sort: 'best', page: 1, pageSize: 12, fields: {}, + seeking: me!.member.seeking, ageMin: me!.member.ageMin, ageMax: me!.member.ageMax, withinMiles: me!.member.maxMiles === undefined ? 50 : me!.member.maxMiles, withPhoto: true, onlineNow: false, everyone: !!me!.member.showEveryone, sort: 'best', page: 1, pageSize: 12, fields: {}, }), [me]); const [filters, setFilters] = useState(defaults); const [draft, setDraft] = useState(filters); @@ -38,6 +38,8 @@ export default function Browse() { useEffect(() => { load(filters); }, [filters, load]); const apply = () => { + // Remember "include everyone" so Discover and the next visit follow it too. + if (site.nicheIncludeLabel && !!draft.everyone !== !!me!.member.showEveryone) api.updateMe({ showEveryone: !!draft.everyone }).then(() => refreshMe()).catch(() => {}); const clamp = (v: string, fallback: number) => Math.min(99, Math.max(18, Number(v) || fallback)); let lo = clamp(ageFrom, 18), hi = clamp(ageTo, 99); if (lo > hi) [lo, hi] = [hi, lo]; @@ -80,6 +82,12 @@ export default function Browse() { setDraft({ ...draft, withPhoto: v })} /> setDraft({ ...draft, onlineNow: v })} /> + {site.nicheIncludeLabel ? ( + + setDraft({ ...draft, everyone: v })} /> + By default, {site.name} shows members who share the site's focus. Tick this to see everyone. + + ) : null} {filterable.length ? ( setShowMore(!showMore)} style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: 6, borderTopWidth: 1, borderColor: t.line, paddingTop: 14 }}> diff --git a/apps/member/src/app/admin/index.tsx b/apps/member/src/app/admin/index.tsx index 342f744..9b55f11 100644 --- a/apps/member/src/app/admin/index.tsx +++ b/apps/member/src/app/admin/index.tsx @@ -197,7 +197,7 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited : ( <> {tab === 'overview' ? <> setTab('moderation')} /> : null} - {tab === 'moderation' ? : null} + {tab === 'moderation' ? : null} {tab === 'members' ? : null} {tab === 'fields' ? : null} {tab === 'events' ? : null} @@ -252,12 +252,14 @@ function Overview({ stats, site }: { stats: SiteStats | null; site: Site; go: (t const CONTACT_FLAG = 'contact info in profile'; const KIND_LABEL: Record = { email: 'email', url: 'link', phone: 'phone number', handle: 'app handle' }; -function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; onChange: () => void }) { +function Moderation({ api, siteId, niche, onChange }: { api: AdminApi; siteId: string; niche?: boolean; onChange: () => void }) { const t = useTheme(); const [status, setStatus] = useState<'pending' | 'all'>('pending'); const [items, setItems] = useState(null); const [big, setBig] = useState(null); const [recheck, setRecheck] = useState<{ busy: boolean; note?: string }>({ busy: false }); + const [nicheRun, setNicheRun] = useState<{ busy: boolean; note?: string }>({ busy: false }); + const [openId, setOpenId] = useState(null); const load = useCallback(() => { setItems(null); api.moderation(siteId, status).then(setItems); }, [api, siteId, status]); useEffect(() => { load(); }, [load]); const decide = async (id: string, d: ModerationDecision, text?: string) => { await api.decide(siteId, id, d, text); load(); onChange(); }; @@ -266,6 +268,15 @@ 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"'], + member: ['Account review', 'Looks fine', 'Suspend account'], + }; + const runNiche = async () => { + setNicheRun({ busy: true }); + try { + const r = await api.runNicheChecks(siteId); + setItems(r.items); onChange(); + setNicheRun({ busy: false, note: `Checked ${r.checked} members. ${r.flagged === 0 ? 'Nothing new to review.' : r.flagged === 1 ? '1 new account to review.' : `${r.flagged} new accounts to review.`}` }); + } catch (e) { setNicheRun({ busy: false, note: e instanceof ApiError ? e.message : 'Check failed.' }); } }; 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,6 +300,13 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; ) : null} {recheck.note ? {recheck.note} : null} + {niche ? ( + + + Looks for answers that don't add up (stated condition vs. height and gender) and fetish or "third" wording. Accounts marked fine stay closed unless their answers change. + + ) : null} + {nicheRun.note ? {nicheRun.note} : null} {!items ? : items.length === 0 ? Nothing waiting. New uploads, held messages and reports land here. : items.map((i) => ( {i.photo ? ( @@ -298,13 +316,13 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; ) : ( - + )} {labels[i.kind][0]} - {i.kind === 'report' ? 'about' : 'from'} {i.memberName} · {relTime(i.createdAt)} + {i.kind === 'report' || i.kind === 'member' ? 'about' : 'from'} {i.memberName} · {relTime(i.createdAt)} {i.status !== 'pending' ? : null} {i.messageBody ? "{i.messageBody}" : null} @@ -312,16 +330,22 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; ? decide(i.id, d, text)} rejectLabel={labels.profile[2]} approveLabel={labels.profile[1]} /> : ( <> - {i.summary} + {i.kind !== 'member' ? {i.summary} : null} - {i.reasons.map((r) => )} + {i.reasons.map((r) => )} + {i.signals?.length ? ( + + {i.signals.map((sig) => {sig})} + + ) : null} {i.status === 'pending' ? ( decide(i.id, 'approve')} /> - decide(i.id, 'reject')} /> + decide(i.id, 'reject')} /> + {i.kind === 'member' ? setOpenId(i.memberId)} /> : null} - ) : null} + ) : i.kind === 'member' ? setOpenId(i.memberId)} /> : null} )} {i.status !== 'pending' ? Decided by {i.decidedBy} {i.decidedAt ? relTime(i.decidedAt) : ''} : null} @@ -329,6 +353,7 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; ))} setBig(null)} /> + setOpenId(null)} /> ); } diff --git a/apps/member/src/ui/FieldsEditor.tsx b/apps/member/src/ui/FieldsEditor.tsx index 202de0e..9360909 100644 --- a/apps/member/src/ui/FieldsEditor.tsx +++ b/apps/member/src/ui/FieldsEditor.tsx @@ -42,7 +42,13 @@ export function FieldsEditor({ fields, value, onChange, onlyRequired }: { case 'number': return set(f.key, v === '' ? undefined : Number(v))} />; default: - return set(f.key, v)} />; + return ( + + set(f.key, v)} maxLength={f.maxLength ?? 200} + multiline={f.multiline} style={f.multiline ? { minHeight: 96, textAlignVertical: 'top' } : undefined} /> + {f.sensitive ? Encrypted and only shown to signed-in members. : null} + + ); } })} @@ -61,14 +67,14 @@ function HeightInput({ label, cm, onChange }: { label: string; cm?: number; onCh if (units === 'metric') return; const f = Number(ft), i = Number(inch || 0); if (ft === '') onChange(undefined); - else if (f >= 3 && f <= 8 && i >= 0 && i < 12) onChange(feetInchesToCm(f, i)); + else if (f >= 2 && f <= 8 && i >= 0 && i < 12) onChange(feetInchesToCm(f, i)); }, [ft, inch]); // eslint-disable-line react-hooks/exhaustive-deps const other = cm ? (units === 'metric' ? `${fi!.ft}′ ${fi!.inch}″` : `${cm} cm`) : ''; return ( {units === 'metric' ? ( { setMetric(v); const n = Number(v); onChange(v === '' ? undefined : n >= 90 && n <= 250 ? n : cm); }} /> + onChangeText={(v) => { setMetric(v); const n = Number(v); onChange(v === '' ? undefined : n >= 60 && n <= 250 ? n : cm); }} /> ) : ( diff --git a/infra/import-members.md b/infra/import-members.md index 56e5a96..85aab3e 100644 --- a/infra/import-members.md +++ b/infra/import-members.md @@ -60,8 +60,8 @@ Note that the dev "Load demo data" deploy option wipes all member data on dev, i | Country, state, city, ZIP, coordinates | The town (city-level coordinates only, never an address) | | "Tell us about you" + "Who I'd like to meet" (SkaDate: About me + In my own words + About the person I want to meet) | About me (second paragraph "Who I'd like to meet: ...") | | AfterH STD type | Status: HSV 1 (oral or genital) → HSV-1, HSV 2 → HSV-2, HPV → HPV; SkaDate also "HSV type unknown" → Herpes (type unsure), "Other STD" → Other | -| HFriends Type of disability + Type of disorder | About my disability: paraplegic/quadriplegic/spinal/spina bifida → Wheelchair user; mobility/physical/amputee/CP and similar → Uses a mobility aid; hearing → Deaf or hard of hearing; vision → Blind or low vision; learning disabled/Asperger's → Neurodivergent; other conditions → Chronic illness | -| DateALittle Dwarfism type | Stature: "None" → Average height, any type → Little person | +| HFriends Type of disability + Type of disorder | About my disability (broad categories, multi): paraplegic/quadriplegic/hemiplegic/spinal/spina bifida → Wheelchair user; mobility/CP/polio/MD → Uses a mobility aid; amputee → Limb difference or amputee; physically impaired/brittle bone → Other physical disability; hearing → Deaf or hard of hearing; vision → Blind or low vision; speech → Speech or communication; learning → Learning or intellectual disability; Asperger's → Neurodivergent; bipolar/depression/schizophrenia → Mental health; "Other" → Other; other conditions → Chronic illness; "No Disability" → No disability ("None" under Type of disorder means no disorder and is ignored). Ticking "No Disability" with other boxes is kept so the review check flags it. | +| DateALittle Dwarfism type | Stature: "None" → Average height; "Short Stature" → Short stature; any type → Little person. Type of dwarfism: the old type mapped to the new list (rare types → Another type). | | Looking for (Something serious / Dates / Sex / Friendship / Chat; SkaDate Here for) | Relationship goal: Long-term / Dating / Friendship (the most committed choice wins) | | Have kids + want kids | Kids | | Smoking, drinking, height | Smoking, drinking, height (cm) | @@ -110,3 +110,8 @@ npm run import -w @whatbox/api -- load --site afterh --bundle /tmp/b --dry-run ``` A folder given to `--bundle` can hold several bundles; they load in name order, first one winning. + + +## Niche review flags (DateALittle, HFriends) + +The load also runs the niche checks (packages/core/src/niche.ts) and puts accounts whose answers don't add up, or whose About me has fetish or "third" wording, in Owner Admin → Moderation as "Account review". Counts by reason appear under "niche" in the report. Nothing is suspended automatically. Owner Admin → Moderation → "Check all members" runs the same checks on demand. diff --git a/packages/core/src/api.ts b/packages/core/src/api.ts index 38a34d5..9be7404 100644 --- a/packages/core/src/api.ts +++ b/packages/core/src/api.ts @@ -88,6 +88,7 @@ export interface AdminApi { decide(siteId: string, itemId: string, decision: ModerationDecision, text?: string): Promise; /** Marks waiting "contact info in profile" items fine when today's check no longer finds contact details. */ recheckModeration(siteId: string): Promise<{ cleared: number; items: ModerationView[] }>; + runNicheChecks(siteId: string): Promise<{ checked: number; flagged: number; items: ModerationView[] }>; members(siteId: string, opts: { search?: string; page?: number }): Promise<{ total: number; page: number; rows: AdminMemberRow[] }>; memberProfile(siteId: string, memberId: string): Promise; setMemberStatus(siteId: string, memberId: string, status: MemberStatus): Promise<{ ok: boolean }>; @@ -201,6 +202,7 @@ export function createLocalAdminApi(platform: Platform): AdminApi { moderation: (s, st) => wrap(async () => platform.adminModeration(await admin(), s, st)), decide: (s, i, d, text) => wrap(async () => platform.adminDecide(await admin(), s, i, d, text)), recheckModeration: (s) => wrap(async () => platform.adminRecheckModeration(await admin(), s)), + runNicheChecks: (s) => wrap(async () => platform.adminRunNicheChecks(await admin(), s)), members: (s, o) => wrap(async () => platform.adminMembers(await admin(), s, o)), memberProfile: (s, m) => wrap(async () => platform.adminMemberProfile(await admin(), s, m)), setMemberStatus: (s, m, st) => wrap(async () => platform.adminSetMemberStatus(await admin(), s, m, st)), diff --git a/packages/core/src/http-client.ts b/packages/core/src/http-client.ts index 0e16b78..ca5278e 100644 --- a/packages/core/src/http-client.ts +++ b/packages/core/src/http-client.ts @@ -154,6 +154,7 @@ export function createHttpAdminApi(baseUrl: string): AdminApi { moderation: (id, status) => req('GET', s(id) + '/moderation?status=' + status), decide: (id, item, decision, text) => req('POST', s(id) + '/moderation/' + item, { decision, text }), recheckModeration: (id) => req('POST', s(id) + '/moderation-recheck', {}), + runNicheChecks: (id) => req('POST', s(id) + '/niche-checks', {}), members: (id, o) => req('GET', s(id) + '/members?search=' + encodeURIComponent(o.search ?? '') + '&page=' + (o.page ?? 1)), memberProfile: (id, m) => req('GET', s(id) + '/members/' + encodeURIComponent(m)), setMemberStatus: (id, m, status) => req('PATCH', s(id) + '/members/' + m, { status }), diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index faea7c8..5dad14d 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,5 +1,6 @@ export * from './types'; export * from './rules'; +export * from './niche'; export * from './crypto'; export * from './geo'; export * from './repo'; diff --git a/packages/core/src/niche.ts b/packages/core/src/niche.ts new file mode 100644 index 0000000..1da7250 --- /dev/null +++ b/packages/core/src/niche.ts @@ -0,0 +1,238 @@ +// Keeping a niche site on-niche (DateALittle: dwarfism and short stature; HFriends: disability). +// +// 1. Browse and Discover show members inside the niche by default; a member can choose to include everyone. +// 2. Review flags for Owner Admin when a profile's answers don't add up (for example "average height" +// with a height of 3'4", or a dwarfism type with an average height), or when wording suggests a +// fetish/"gawker" account or a couple looking for a "third". Nothing here bans anyone: it only puts +// the member in the moderation queue, and the site admin decides. +// Pure functions, unit tested in test/niche.test.ts. +import { formatHeight } from './rules'; +import type { Gender, Member, NicheSettings, ProfileFieldDef, Site } from './types'; + +// ---------------- Field definitions ---------------- + +/** DateALittle "Type of dwarfism": the old site's list, tidied. One per member. */ +export const DWARFISM_TYPES = [ + 'Achondroplasia', 'Hypochondroplasia', 'Pseudoachondroplasia', 'Diastrophic dysplasia', + 'Spondyloepiphyseal dysplasia (SED)', 'Spondyloepimetaphyseal dysplasia (SEMD)', 'Spondylometaphyseal dysplasia (SMD)', + 'Multiple epiphyseal dysplasia (MED)', 'Metaphyseal chondrodysplasia', 'Acromesomelic dysplasia', 'Mesomelic dysplasia', + 'Campomelic dysplasia', 'Chondrodysplasia punctata', 'Cleidocranial dysplasia', 'Ellis-van Creveld syndrome', + 'Kniest dysplasia', 'Larsen syndrome', 'Leri-Weill dyschondrosteosis', 'Metatropic dysplasia', + 'Osteogenesis imperfecta (OI)', 'Morquio syndrome (MPS IV)', 'Other mucopolysaccharidosis (MPS)', + 'Primordial dwarfism (MOPD, Seckel)', 'Russell-Silver syndrome', 'Turner syndrome', 'Growth hormone deficiency', + 'Laron syndrome', 'Pituitary or hormonal', 'Hypophosphatemia or rickets', 'Another type', + 'Not sure / no diagnosis', 'Prefer not to say', +] as const; +const NOT_A_TYPE = new Set(['Not sure / no diagnosis', 'Prefer not to say']); + +export const STATURE_FIELD: ProfileFieldDef = { + key: 'stature', label: 'Stature', type: 'select', options: ['Little person', 'Short stature', 'Average height', 'Prefer not to say'], + required: true, filterable: true, showOnProfile: true, section: 'details', order: 1, +}; +export const DWARFISM_TYPE_FIELD: ProfileFieldDef = { + key: 'dwarfism_type', label: 'Type of dwarfism', type: 'select', options: [...DWARFISM_TYPES], + showOnProfile: true, sensitive: true, section: 'details', order: 1.5, +}; + +/** HFriends: broad categories, no diagnosis needed. Pick all that apply. */ +export const DISABILITY_CATEGORIES = [ + 'Wheelchair user', 'Uses a mobility aid', 'Other physical disability', 'Limb difference or amputee', + 'Deaf or hard of hearing', 'Blind or low vision', 'Speech or communication', 'Learning or intellectual disability', + 'Neurodivergent', 'Chronic illness', 'Mental health', 'Other', 'No disability', 'Prefer not to say', +] as const; +export const ACCESSIBILITY_FIELD: ProfileFieldDef = { + key: 'accessibility', label: 'About my disability', type: 'multiselect', options: [...DISABILITY_CATEGORIES], + exclusive: ['No disability', 'Prefer not to say'], filterable: true, showOnProfile: true, sensitive: true, section: 'details', order: 1, +}; +export const DISABILITY_DETAILS_FIELD: ProfileFieldDef = { + key: 'disability_details', label: 'More about my disability (optional)', type: 'text', maxLength: 500, multiline: true, + showOnProfile: true, sensitive: true, section: 'details', order: 1.5, +}; + +export const DATEALITTLE_NICHE: NicheSettings = { + kind: 'dwarfism', field: 'stature', outside: ['Average height'], + includeLabel: 'Include average-height members', +}; +export const HFRIENDS_NICHE: NicheSettings = { + kind: 'disability', field: 'accessibility', outside: ['No disability'], + includeLabel: 'Include members without a disability', +}; + +/** Brings DateALittle and HFriends up to the fields and niche settings above. Keeps options an admin added. Safe to re-run. */ +export function upgradeNicheFields(site: Site): boolean { + const before = JSON.stringify({ f: site.fields, n: site.settings.niche }); + const merge = (want: ProfileFieldDef, extra: ProfileFieldDef[] = []) => { + const i = site.fields.findIndex((f) => f.key === want.key); + if (i < 0) { site.fields.push({ ...want }); return; } + const cur = site.fields[i]; + const options = [...(want.options ?? []), ...(cur.options ?? []).filter((o) => !want.options?.includes(o))]; + site.fields[i] = { ...cur, type: want.type, options, ...(want.exclusive ? { exclusive: want.exclusive } : {}) }; + for (const e of extra) if (!site.fields.some((f) => f.key === e.key)) site.fields.push({ ...e, order: cur.order + 0.5 }); + }; + if (site.slug === 'datealittle') { + merge(STATURE_FIELD, [DWARFISM_TYPE_FIELD]); + site.settings.niche ??= { ...DATEALITTLE_NICHE }; + } else if (site.slug === 'hfriends') { + merge(ACCESSIBILITY_FIELD, [DISABILITY_DETAILS_FIELD]); + site.settings.niche ??= { ...HFRIENDS_NICHE }; + } else return false; + return JSON.stringify({ f: site.fields, n: site.settings.niche }) !== before; +} + +// ---------------- Browse default ---------------- + +/** True when the member's answer puts them outside the site's niche. No answer, or "Prefer not to say", stays inside. */ +export function outsideNiche(site: Site, m: Pick): boolean { + const n = site.settings.niche; + if (!n) return false; + const v = m.fields[n.field]; + if (Array.isArray(v)) return v.length > 0 && v.every((x) => n.outside.includes(x)); + return typeof v === 'string' && n.outside.includes(v); +} + +// ---------------- Review flags ---------------- + +export interface NicheFlag { + /** Stable code, so the same concern isn't raised twice. */ + code: 'stature_short' | 'stature_tall' | 'stature_mixed' | 'disability_mixed' | 'disability_all' | 'couple_third' | 'fetish'; + reason: string; + signals: string[]; +} + +const isWomanish = (g: Gender) => g === 'woman' || g === 'trans_ftm'; +const isManish = (g: Gender) => g === 'man'; + +/** Heights in cm. "Average height" members this short, or little people this tall, get a second look. */ +export const STATURE_LIMITS = { + /** Says average height, but 4'6" or shorter. */ + averageMax: 137, + /** Says little person (or names a dwarfism type), but at least this tall: women 5'2", men 5'4", everyone else 5'3". */ + littleMin: { woman: 157, man: 163, other: 160 }, + /** Says short stature (no dwarfism), but at least: women 5'5", men 5'9", everyone else 5'7". */ + shortMin: { woman: 165, man: 175, other: 170 }, +}; +const forGender = (g: Gender, t: { woman: number; man: number; other: number }) => (isWomanish(g) ? t.woman : isManish(g) ? t.man : t.other); + +/** Answers that don't add up for this site's niche (height, gender and stated condition). */ +export function profileFlags(site: Site, m: Pick): NicheFlag[] { + const kind = site.settings.niche?.kind; + const out: NicheFlag[] = []; + const h = typeof m.fields.height === 'number' ? m.fields.height : undefined; + const ht = (cm: number) => `${formatHeight(cm, 'imperial')} (${cm} cm)`; + const gender = GENDER_LABEL[m.gender] ?? m.gender; + if (kind === 'dwarfism') { + const stature = typeof m.fields.stature === 'string' ? m.fields.stature : undefined; + const type = typeof m.fields.dwarfism_type === 'string' ? m.fields.dwarfism_type : undefined; + const namesType = !!type && !NOT_A_TYPE.has(type); + const facts = [`Stature: ${stature ?? 'not answered'}`, ...(type ? [`Type of dwarfism: ${type}`] : []), ...(h ? [`Height: ${ht(h)}`] : []), `Gender: ${gender}`]; + if (stature === 'Average height' && h !== undefined && h <= STATURE_LIMITS.averageMax) { + out.push({ code: 'stature_short', reason: 'Says average height, but is very short', signals: facts }); + } + if ((stature === 'Little person' || (namesType && stature !== 'Average height')) && h !== undefined && h >= forGender(m.gender, STATURE_LIMITS.littleMin)) { + out.push({ code: 'stature_tall', reason: 'Says little person, but height is average', signals: facts }); + } else if (stature === 'Short stature' && h !== undefined && h >= forGender(m.gender, STATURE_LIMITS.shortMin)) { + out.push({ code: 'stature_tall', reason: 'Says short stature, but height is average', signals: facts }); + } + if (stature === 'Average height' && namesType) { + out.push({ code: 'stature_mixed', reason: 'Says average height, but also names a type of dwarfism', signals: facts }); + } + } + if (kind === 'disability') { + const v = Array.isArray(m.fields.accessibility) ? (m.fields.accessibility as string[]) : []; + const real = v.filter((x) => x !== 'No disability' && x !== 'Prefer not to say'); + if (v.includes('No disability') && real.length) { + out.push({ code: 'disability_mixed', reason: 'Says no disability, but also picked disabilities', signals: [`About my disability: ${v.join(', ')}`] }); + } + if (real.length >= DISABILITY_ALL_MIN) { + out.push({ code: 'disability_all', reason: 'Picked almost every disability type', signals: [`About my disability: ${v.join(', ')}`] }); + } + } + return out; +} + +/** Picking this many categories (of 12) looks like ticking every box, a pattern Jeff saw from gawkers on the old site. */ +export const DISABILITY_ALL_MIN = 8; + +const GENDER_LABEL: Record = { woman: 'Woman', man: 'Man', nonbinary: 'Non-Binary', trans_mtf: 'Trans M2F', trans_ftm: 'Trans F2M' }; + +// Wording. Written to catch the obvious cases; an admin reviews every hit, so a false positive costs a click. +const PARTNER = '(?:wife|husband|hubby|partner|girlfriend|boyfriend|gf|bf|fianc[eé]e?)'; +const COUPLE_THIRD: RegExp[] = [ + /\bunicorns?\b/i, + /\b(?:looking for|seeking|searching for|want|need|find|for) (?:a|our) (?:third|3rd)\b(?! (?:date|time|year|grade|shift|job|child|kid|son|daughter|place))/i, + /\bour (?:third|3rd)\b(?! (?:date|time|year|anniversary|child|kid|son|daughter))/i, + /\b(?:threesomes?|three[- ]?somes?|3[- ]?somes?|ffm|mfm|mmf|fmf)\b/i, + new RegExp(`\\bjoin (?:us|me and my ${PARTNER}|my ${PARTNER} and (?:me|i))\\b`, 'i'), + new RegExp(`\\b(?:my|our) ${PARTNER} and i (?:are|want|would|like|love|enjoy|both|have been)\\b`, 'i'), + new RegExp(`\\bme and my ${PARTNER} (?:are|want|would|like|love|enjoy)\\b`, 'i'), + /\bwe(?:'re| are) an? (?:(?:happily|open|married|fun|attractive|loving|young|bi|bisexual)[ ,]+)*couple\b/i, + /\b(?:couple|we(?:'re| are)) (?:looking|seeking|searching) for (?:a |another )?(?:woman|girl|lady|man|guy|female|male|playmate|friend to (?:play|join))\b/i, + /\b(?:hot ?wife|cuckold|cuck|swingers?|lifestyle couple|for us both|to share with my (?:wife|husband))\b/i, +]; +const SMALL = '(?:little|small|short|tiny|petite|dwarf|midget)'; +const SMALL_PERSON = `(?:midgets?|dwarfs?|${SMALL} (?:people|persons?|women|woman|girls?|ladies|lady|men|man|guys?))`; +const FETISH_COMMON: RegExp[] = [ + /\bfetish\w*/i, + /\bkink(?:s|y)?\b/i, +]; +const FETISH_DWARFISM: RegExp[] = [ + /\bmidgets?\b/i, + new RegExp(`\\b(?:always|never) (?:wanted|been curious|had the chance) to (?:try|be with|date|sleep with|have sex with|f\\w*k|hook up with) (?:a |an )?${SMALL}`, 'i'), + new RegExp(`\\b(?:curious about|obsessed with|attracted only to|only into|turned on by) ${SMALL} (?:people|persons?|women|woman|girls?|ladies|men|guys?)\\b`, 'i'), + new RegExp(`\\b${SMALL} (?:people|women|woman|girls?|ladies|men|guys?) (?:turn me on|are (?:so )?(?:hot|sexy))\\b`, 'i'), + /\b(?:dwarf|midget) (?:porn|sex|lover|lovers|chaser)\b/i, + /\b(?:size difference|pocket[- ]sized?)\b/i, + new RegExp(`${SMALL_PERSON}[^.!?\\n]{0,40}\\bbucket list|\\bbucket list[^.!?\\n]{0,40}${SMALL_PERSON}`, 'i'), +]; +const FETISH_DISABILITY: RegExp[] = [ + /\bdevotees?\b/i, + /\bpretenders?\b/i, + /\b(?:amputee|stump|wheelchair|brace|cast|crutch) (?:lover|admirer|fan|chaser|fetish)s?\b/i, + /\b(?:stumps|amputees|wheelchairs|leg braces|crutches) (?:turn me on|are (?:so )?(?:hot|sexy))\b/i, + /\b(?:always|never) (?:wanted|been curious) to (?:try|be with|date|sleep with|have sex with) (?:a |an )?(?:amputee|disabled|paraplegic|quadriplegic|wheelchair)/i, +]; + +/** Where in a text the wording checks hit, with a short excerpt around each hit. */ +export function textFlags(site: Site, text: string, where: string): NicheFlag[] { + const kind = site.settings.niche?.kind; + if (!kind || !text) return []; + const out: NicheFlag[] = []; + // "No devotees", "not into kink": a hit right after a negation is the member setting a boundary, not a red flag. + const negated = (h: RegExpExecArray) => + /\b(?:no|not|non|don'?t|do not|never|without|anti|zero|nor|aren'?t|isn'?t)\b[^.!?\n]{0,20}$/i.test(text.slice(Math.max(0, h.index - 30), h.index)) + || /^[\s,:-]{0,3}(?:are |is |need )?(?:not welcome|not allowed|need not apply|not apply|unwelcome|not wanted|stay away|keep away|go away|move on|keep scrolling|swipe left)/i.test(text.slice(h.index + h[0].length, h.index + h[0].length + 30)); + const first = (re: RegExp) => { + for (const h of text.matchAll(new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g'))) if (!negated(h as RegExpExecArray)) return h as RegExpExecArray; + return null; + }; + const hits = (res: RegExp[]) => res.map(first).filter((x): x is RegExpExecArray => !!x); + const couple = hits(COUPLE_THIRD); + if (couple.length) out.push({ code: 'couple_third', reason: 'May be a couple looking for a "third"', signals: [...new Set(couple.map((h) => `${where}: "${excerpt(text, h.index, h[0].length)}"`))].slice(0, 3) }); + const fetish = hits([...FETISH_COMMON, ...(kind === 'dwarfism' ? FETISH_DWARFISM : FETISH_DISABILITY)]); + if (fetish.length) out.push({ code: 'fetish', reason: 'Wording suggests a fetish or "gawker" interest', signals: [...new Set(fetish.map((h) => `${where}: "${excerpt(text, h.index, h[0].length)}"`))].slice(0, 3) }); + return out; +} + +export function excerpt(text: string, at: number, len: number, pad = 60): string { + const s = Math.max(0, at - pad), e = Math.min(text.length, at + len + pad); + return (s > 0 ? '…' : '') + text.slice(s, e).replace(/\s+/g, ' ').trim() + (e < text.length ? '…' : ''); +} + +/** Every flag for a member's profile: answers plus the wording of About me and any free-text fields. */ +export function memberFlags(site: Site, m: Pick): NicheFlag[] { + if (!site.settings.niche) return []; + const flags = profileFlags(site, m); + const texts: [string, string][] = [['About me', m.about]]; + for (const def of site.fields) if (def.type === 'text' && typeof m.fields[def.key] === 'string') texts.push([def.label, m.fields[def.key] as string]); + for (const [where, t] of texts) mergeFlags(flags, textFlags(site, t, where)); + return flags; +} + +export function mergeFlags(into: NicheFlag[], more: NicheFlag[]) { + for (const f of more) { + const cur = into.find((x) => x.code === f.code); + if (cur) cur.signals = [...new Set([...cur.signals, ...f.signals])].slice(0, 6); + else into.push({ ...f, signals: [...f.signals] }); + } + return into; +} diff --git a/packages/core/src/seed.ts b/packages/core/src/seed.ts index 6476a58..b797550 100644 --- a/packages/core/src/seed.ts +++ b/packages/core/src/seed.ts @@ -2,6 +2,7 @@ import { lookupPostal } from './geo'; import { DEFAULT_MEMBERSHIP } from './rules'; import { starterPages } from './starter-content'; +import { ACCESSIBILITY_FIELD, DATEALITTLE_NICHE, DISABILITY_DETAILS_FIELD, DWARFISM_TYPE_FIELD, HFRIENDS_NICHE, STATURE_FIELD, upgradeNicheFields } from './niche'; import { DEFAULT_LICENSING } from './types'; import type { AdminUser, ContentPage, Gender, Member, Message, ModerationItem, Photo, PrivateAccess, ProfileFieldDef, Site, @@ -60,8 +61,9 @@ export const STATUS_FIELD: ProfileFieldDef = { /** Brings older site field definitions up to date. Returns true if anything changed. */ export function upgradeSiteFields(site: Site): boolean { + const niche = upgradeNicheFields(site); const i = site.fields.findIndex((f) => f.key === 'hsv_status' && f.type === 'select'); - if (i < 0) return false; + if (i < 0) return niche; site.fields[i] = { ...STATUS_FIELD, label: site.fields[i].label, order: site.fields[i].order }; return true; } @@ -112,9 +114,10 @@ export function seedSites(now: Date): Site[] { ground: '#F2F6FA', surface: '#FFFFFF', ink: '#16263A', sub: '#43556B', line: '#DCE4EE', accent: '#2F5D8A', accentSoft: '#E1EBF5', second: '#E0B23C', alert: '#9A4A2E', ...HFRIENDS_TYPE, radius: 10, style: 'accessible', }, - settings: settings({ mode: 'standard', publicTeasers: true }), + settings: settings({ mode: 'standard', publicTeasers: true, niche: { ...HFRIENDS_NICHE } }), fields: [ - { key: 'accessibility', label: 'About my disability', type: 'multiselect', options: ['Wheelchair user', 'Uses a mobility aid', 'Deaf or hard of hearing', 'Blind or low vision', 'Chronic illness', 'Neurodivergent', 'Prefer not to say'], filterable: true, showOnProfile: true, sensitive: true, section: 'details', order: 1 }, + ACCESSIBILITY_FIELD, + DISABILITY_DETAILS_FIELD, ...commonFields(2), ], ownerIds: ['adm_owner'], createdAt: created, status: 'active', licensing: { ...DEFAULT_LICENSING, owned: true }, @@ -128,9 +131,10 @@ export function seedSites(now: Date): Site[] { accentSoft: '#F0E6F4', second: '#3E9C8C', alert: '#9A4A2E', headingFont: 'Nunito', bodyFont: 'Figtree', radius: 16, style: 'warm', fontsHref: 'https://fonts.googleapis.com/css2?family=Nunito:wght@700;800&family=Figtree:wght@400;500;600;700&display=swap', }, - settings: settings({ mode: 'standard', publicTeasers: true }), + settings: settings({ mode: 'standard', publicTeasers: true, niche: { ...DATEALITTLE_NICHE } }), fields: [ - { key: 'stature', label: 'Stature', type: 'select', options: ['Little person', 'Average height', 'Prefer not to say'], required: true, filterable: true, showOnProfile: true, section: 'details', order: 1 }, + STATURE_FIELD, + DWARFISM_TYPE_FIELD, ...commonFields(2), ], ownerIds: ['adm_owner'], createdAt: created, status: 'active', licensing: { ...DEFAULT_LICENSING, owned: true }, @@ -219,6 +223,13 @@ export function seedSite(site: Site, now: Date, opts: { demoMemberHash?: { email else if (f.type === 'height') fields[f.key] = (gender === 'man' ? 170 : 155) + ((i * 37) % 23); else if (f.type === 'multiselect' && f.options) fields[f.key] = some(r, f.options.filter((o) => o !== 'Prefer not to say'), f.key === 'interests' ? 3 + Math.floor(r() * 3) : 1); } + // DateALittle demo people: height and type that match their stature, so the review checks stay quiet + if (typeof fields.stature === 'string') { + const base = fields.stature === 'Little person' ? 100 : fields.stature === 'Short stature' ? 142 : fields.stature === 'Average height' ? (gender === 'man' ? 170 : 158) : 0; + if (base) fields.height = base + ((i * 37) % 15); else delete fields.height; + if (fields.stature === 'Little person') fields.dwarfism_type = pick(r, ['Achondroplasia', 'Achondroplasia', 'Hypochondroplasia', 'Diastrophic dysplasia', 'Spondyloepiphyseal dysplasia (SED)', 'Prefer not to say']); + else delete fields.dwarfism_type; + } const online = r() < 0.3; const m: Member = { id: `m_${site.slug}_${i + 1}`, displayName: name, verifiedAt: t(60 * 24 * (20 + i)), profileComplete: true, @@ -264,7 +275,7 @@ export function seedSite(site: Site, now: Date, opts: { demoMemberHash?: { email if (f.key === 'hsv_status') demo.fields[f.key] = ['HSV-1']; else if (f.key === 'interests') demo.fields[f.key] = ['Hiking', 'Cooking', 'Live music', 'Dogs']; else if (f.key === 'relationship_goal') demo.fields[f.key] = 'Long-term'; - else if (f.type === 'height') demo.fields[f.key] = 180; + else if (f.type === 'height') demo.fields[f.key] = fieldDefs.some((d) => d.key === 'stature') ? 122 : 180; else if (f.type === 'select' && f.options) demo.fields[f.key] = f.options[0]; else if (f.type === 'multiselect' && f.options) demo.fields[f.key] = [f.options[0]]; } diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts index 08f7063..8eaed34 100644 --- a/packages/core/src/services.ts +++ b/packages/core/src/services.ts @@ -3,6 +3,7 @@ import { LocalEventHub } from './events'; import { DevKeyProvider, hmacHex, type KeyProvider, randomCode, randomId, SiteCrypto } from './crypto'; import { builtinGeo, unitsForCountry } from './geo'; +import { memberFlags, type NicheFlag, outsideNiche, textFlags } from './niche'; import { buildSiteDashboard, cleanHitPath, combineDashboards, DASHBOARD_DAYS, emptySiteDashboard, isBotAgent, publicGoogleTags, referrerHost, utcDay, addDays, validateGoogleTags, } from './analytics'; @@ -63,6 +64,8 @@ export interface ProfilePatch { notify?: Partial; hiddenPrefs?: HiddenPrefs; showEvents?: boolean; + /** Niche sites: Browse and Discover include members outside the niche too. */ + showEveryone?: boolean; about?: string; fields?: Member['fields']; hideExplicit?: boolean; @@ -130,6 +133,7 @@ export class Platform { explicitPhotosAllowed: site.settings.explicitPhotosAllowed, publicTeasers: site.settings.mode !== 'sensitive' && site.settings.publicTeasers, units: site.settings.units, + nicheIncludeLabel: site.settings.niche?.includeLabel, googleTags: publicGoogleTags(site), }; } @@ -446,6 +450,7 @@ export class Platform { m.strict = cur; } if (typeof patch.showEvents === 'boolean') m.showEvents = patch.showEvents; + if (typeof patch.showEveryone === 'boolean') m.showEveryone = patch.showEveryone; if (patch.hiddenPrefs) { const cur = { ...m.hiddenPrefs }; for (const k of ['seeking', 'ages'] as const) if (typeof patch.hiddenPrefs[k] === 'boolean') cur[k] = patch.hiddenPrefs[k]; @@ -462,6 +467,7 @@ export class Platform { m.about = patch.about.trim(); if (m.profileComplete && m.about) await this.flagProfileText(ctx, m.about); } + const nicheCheck = patch.about !== undefined || patch.fields !== undefined || patch.gender !== undefined; if (patch.fields) { for (const [key, value] of Object.entries(patch.fields)) { const def = ctx.site.fields.find((f) => f.key === key); @@ -478,6 +484,9 @@ export class Platform { if (m.displayName && m.city && !missing.length) m.profileComplete = true; } await ctx.repo.saveMember(m); + if (nicheCheck && m.profileComplete) { + for (const f of memberFlags(ctx.site, m)) await flagMember(ctx.repo, m.id, f, this.iso()); + } this.changed(); return this.myProfile(ctx); } @@ -657,6 +666,7 @@ export class Platform { onlyComplete: true, }); if (within && bbox) rows = rows.filter((m) => milesBetween(ctx.me, m) <= within); + if (!(f.everyone ?? ctx.me.showEveryone)) rows = rows.filter((m) => !outsideNiche(ctx.site, m)); if (f.fields) { for (const [key, wanted] of Object.entries(f.fields)) { if (!wanted?.length) continue; @@ -930,6 +940,7 @@ export class Platform { const dLat = within / 69, dLng = within / (69 * Math.max(0.2, Math.cos((ctx.me.lat * Math.PI) / 180))); return { minLat: ctx.me.lat - dLat, maxLat: ctx.me.lat + dLat, minLng: ctx.me.lng - dLng, maxLng: ctx.me.lng + dLng }; }; + const inNiche = (m: Member) => !!ctx.me.showEveryone || !outsideNiche(ctx.site, m); const inPrefs = (m: Member) => { const age = year - m.birthYear; return ctx.me.seeking.includes(m.gender) && age >= ctx.me.ageMin && age <= ctx.me.ageMax && (!miles || !hasLoc || milesBetween(ctx.me, m) <= miles); @@ -937,7 +948,7 @@ export class Platform { let rows = (await ctx.repo.queryMembers({ excludeIds: [...skip], genders: ctx.me.seeking, birthYearMin: year - ctx.me.ageMax, birthYearMax: year - ctx.me.ageMin, bbox: box(miles), onlyComplete: true, - })).filter(inPrefs); + })).filter(inPrefs).filter(inNiche); const stretched = new Map(); if (rows.length < limit && !(strict.seeking && strict.age && strict.distance)) { const more = (await ctx.repo.queryMembers({ @@ -945,7 +956,7 @@ export class Platform { genders: strict.seeking ? ctx.me.seeking : undefined, birthYearMin: strict.age ? year - ctx.me.ageMax : undefined, birthYearMax: strict.age ? year - ctx.me.ageMin : undefined, bbox: strict.distance ? box(miles) : undefined, onlyComplete: true, - })).filter((m) => !strict.distance || !miles || !hasLoc || milesBetween(ctx.me, m) <= miles); + })).filter((m) => !strict.distance || !miles || !hasLoc || milesBetween(ctx.me, m) <= miles).filter(inNiche); for (const m of more) { const age = year - m.birthYear; const why = !ctx.me.seeking.includes(m.gender) ? 'Outside who you said you want to meet' @@ -1274,6 +1285,8 @@ export class Platform { senderTier: this.tierOf(ctx.me), }; await ctx.repo.saveMessage(msg); + // Niche wording (fetish, couples looking for a "third") doesn't hold the message: it puts the sender up for review. + for (const f of textFlags(ctx.site, body, `Message to ${other.displayName}`)) await flagMember(ctx.repo, ctx.me.id, f, this.iso()); if (!screen.hold) this.emit(ctx, other.id, { type: 'message', fromId: ctx.me.id }); if (screen.hold) { await ctx.repo.saveModeration({ @@ -1446,6 +1459,10 @@ export class Platform { const m = await repo.getMessage(item.refId); // approve releases the message to the recipient; reject keeps it held forever if (m && decision === 'approve') await repo.saveMessage({ ...m, held: false, at: this.iso() }); + } else if (item.kind === 'member' && decision === 'reject') { + // "Suspend account": the admin's call, never automatic + const m = await repo.getMember(item.memberId); + if (m) await repo.saveMember({ ...m, status: 'suspended' }); } else if (item.kind === 'report' && decision === 'approve') { const m = await repo.getMember(item.memberId); if (m) await repo.saveMember({ ...m, status: 'suspended' }); @@ -1504,6 +1521,26 @@ export class Platform { return { cleared, items: await this.adminModeration(admin, siteId, 'pending') }; } + /** Niche sites: runs the profile checks (stature vs. height and gender, disability answers, wording) over every + * member, e.g. after an import. Raises only new concerns; ones marked "Looks fine" stay closed for the same answers. */ + async adminRunNicheChecks(admin: AdminUser, siteId: string): Promise<{ checked: number; flagged: number; items: ModerationView[] }> { + const site = await this.adminSite(admin, siteId); + if (!site.settings.niche) throw new RuleError('no_niche', 'This site has no niche checks.'); + const repo = await this.repo(site); + let checked = 0, flagged = 0; + for (let offset = 0; ; offset += 200) { + const { rows } = await repo.listAllMembers(200, offset); + for (const m of rows) { + checked++; + for (const f of memberFlags(site, m)) if (await flagMember(repo, m.id, f, this.iso())) flagged++; + } + if (rows.length < 200) break; + } + await this.audit(admin, 'moderation.niche_checks', site.id, undefined, `${checked} checked, ${flagged} flagged`); + this.changed(); + return { checked, flagged, items: await this.adminModeration(admin, siteId, 'pending') }; + } + /** The member's profile as other members see it, plus every photo (pending, private, rejected) for the admin. * Nothing is recorded: no profile view, no notification. Contact details stay encrypted and are not included. */ async adminMemberProfile(admin: AdminUser, siteId: string, memberId: string): Promise { @@ -1961,7 +1998,32 @@ function validateField(def: ProfileFieldDef, value: unknown) { break; case 'number': if (typeof value !== 'number' || !Number.isFinite(value)) bad(); break; case 'boolean': if (typeof value !== 'boolean') bad(); break; - case 'text': if (typeof value !== 'string' || value.length > 200) bad(); break; - case 'height': if (typeof value !== 'number' || value < 90 || value > 250) bad(); break; + case 'text': if (typeof value !== 'string' || value.length > (def.maxLength ?? 200)) bad(); break; + // DateALittle members can be under 3 feet + case 'height': if (typeof value !== 'number' || value < 60 || value > 250) bad(); break; } } + +/** + * Puts a member up for review for one niche concern. One item per member and concern: while it's waiting, new + * evidence is added to it; once decided, it opens again only if the evidence has changed (so "Looks fine" sticks + * for the same answers). Returns true when an item was created or reopened. + */ +export async function flagMember(repo: SiteRepo, memberId: string, f: NicheFlag, nowIso: string): Promise { + const id = `mod_niche_${f.code}_${memberId}`; + const key = f.signals.slice().sort().join('|'); + const cur = await repo.getModeration(id); + if (cur?.status === 'pending') { + const signals = [...new Set([...(cur.signals ?? []), ...f.signals])].slice(-8); + if (signals.length !== (cur.signals ?? []).length) await repo.saveModeration({ ...cur, signals, evidenceKey: key }); + return false; + } + if (cur && cur.evidenceKey === key) return false; + // a decided profile-answer concern reopens only when the answers changed; wording concerns reopen on new wording + if (cur && f.signals.every((x) => cur.signals?.includes(x))) return false; + await repo.saveModeration({ + id, kind: 'member', refId: memberId, memberId, summary: f.reason, reasons: [f.reason], signals: f.signals, evidenceKey: key, + status: 'pending', createdAt: nowIso, + }); + return true; +} diff --git a/packages/core/src/starter-content.ts b/packages/core/src/starter-content.ts index c2d9919..a38d814 100644 --- a/packages/core/src/starter-content.ts +++ b/packages/core/src/starter-content.ts @@ -24,6 +24,19 @@ const page = (d: Draft, at: string): ContentPage => ({ published: true, ...d, up // ---------- Shared pieces ---------- +const guidelines = (n: string, intro: string, rules: string[]): Draft => ({ + slug: 'community-guidelines', kind: 'page', title: 'Community guidelines', placement: 'footer', + summary: `What ${n} is for, and what gets an account removed.`, + seoTitle: `Community guidelines | ${n}`, + seoDescription: `How ${n} stays a respectful community: who it is for, honest profiles, one person per profile, and what gets an account removed.`, + body: [ + intro, + ...rules, + 'How we enforce this\nOur team reviews profiles and messages that are reported or flagged. Nothing is removed automatically: a person looks first. We may ask you to change your profile, limit your account, or remove it.', + 'See something that does not belong? Report the member from their profile. Reports are private.', + ].join('\n\n'), +}); + const scamGuide = (n: string): Draft => ({ slug: 'spotting-romance-scams', kind: 'article', category: 'Safety', title: 'Spotting romance scams', placement: 'guides', summary: 'Gift cards, overseas emergencies and "let\'s move to WhatsApp": the patterns to watch for.', @@ -228,11 +241,18 @@ function hfriends(site: Site): Draft[] { `Is ${n} free?\nYes. Joining, browsing and messaging are free.`, 'Do I have to say what my disability is?\nNo. You can share it, keep it general, or choose "Prefer not to say". You can change it any time.', 'Can people who are not disabled join?\nYes. Partners, friends and people who want to date someone disabled are welcome, as long as they are respectful. Fetish accounts are removed.', + 'Who will I see when I browse?\nMembers who share a disability, by default. Tick "Include members without a disability" in the filters to see everyone.', 'Can anyone see my profile without an account?\nOnly if you turn on a public teaser in your settings. It is off by default.', 'Does the site work with my screen reader?\nIt should. If anything does not, please tell us so we can fix it.', ].join('\n\n'), }, safetyTips(n, ['Choose a first-date place you know is accessible for you, or call ahead to check. It is fine to suggest the venue yourself.']), + guidelines(n, `${n} is for disabled people and the people who want to date them or be their friends. These guidelines keep it that way.`, [ + 'Be here for the person\nPartners, friends and people who want to date someone disabled are welcome when they are respectful. Treating disability as a fetish ("devotees"), or pretending to be disabled, gets an account removed.', + 'Be honest about yourself\nPick the categories that fit you, or "No disability" if none do. You never have to name a diagnosis. Our team takes a second look at profiles whose answers do not add up.', + 'One person per profile\nProfiles are for individuals who want to date or make friends. Couples looking for a "third", and profiles shared by a couple, are not allowed.', + 'Keep it respectful\nNo slurs, and no pushing for photos of someone\'s disability. Medical questions wait until they invite them.', + ]), privacy(n, site.settings.billingDescriptor, 'Disability and health information. Anything you share about your disability or health is treated as sensitive. It is only shown to signed-in members, only if you choose to show it, and it is never used for advertising.'), terms(n), { @@ -323,12 +343,19 @@ function datealittle(site: Site): Draft[] { body: [ `Is ${n} free?\nYes. Joining, browsing and messaging are free.`, 'Can average-height people join?\nYes, if they are here to meet someone, not to gawk. Fetish and novelty accounts are removed.', - 'Do I have to share my stature?\nYou choose: little person, average height, or "Prefer not to say".', + 'Do I have to share my stature?\nYou choose: little person, short stature, average height, or "Prefer not to say". Naming your type of dwarfism is optional.', + 'Who will I see when I browse?\nLittle people and people with short stature, by default. Tick "Include average-height members" in the filters to see everyone.', 'Can anyone see my profile without an account?\nOnly if you turn on a public teaser in your settings. It is off by default.', 'How do events work?\nMembers can see upcoming meetups and say they are going. Exact addresses are only shared with people who RSVP.', ].join('\n\n'), }, safetyTips(n, ['If you are meeting someone you only know online, a group meetup or a convention social is a great low-pressure first step.']), + guidelines(n, `${n} is for little people, people with short stature, and the people who want to date them. These guidelines keep it that way.`, [ + 'Be here for the person\nAverage-height members are welcome when they come to meet someone, not to gawk. Treating stature as a novelty, a fetish or a bucket-list item gets an account removed.', + 'Be honest about yourself\nAnswer stature and height truthfully. Our team takes a second look at profiles whose answers do not add up.', + 'One person per profile\nProfiles are for individuals who want to date or make friends. Couples looking for a "third", and profiles shared by a couple, are not allowed. What adults do in their own lives is their business, but recruiting for it here is not.', + 'Keep it respectful\nNo slurs, including the "m-word". Questions about someone\'s condition, height or medical history wait until they invite them.', + ]), privacy(n, site.settings.billingDescriptor, 'Personal details. Anything you share about your stature or health is only shown to signed-in members, only if you choose to show it, and it is never used for advertising.'), terms(n), { diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 0f31775..0891e27 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -69,6 +69,18 @@ export interface SiteSettings { }; /** Optional Google Analytics / Google Ads tags. Off unless the owner turns them on. */ googleTags?: GoogleTags; + /** Niche sites (DateALittle, HFriends): who Browse shows by default, and which review checks run. */ + niche?: NicheSettings; +} + +export interface NicheSettings { + kind: 'dwarfism' | 'disability'; + /** The profile field that says whether a member is part of the niche. */ + field: string; + /** Answers that mean "not part of the niche". No answer and "Prefer not to say" still count as inside. */ + outside: string[]; + /** Browse checkbox that includes everyone else. */ + includeLabel: string; } /** @@ -115,6 +127,9 @@ export interface ProfileFieldDef { exclusive?: string[]; /** When a member picks this option, everyone viewing their profile sees this message in red. */ caution?: { option: string; message: string }; + /** text only: longest answer (default 200), and whether it gets a multi-line box. */ + maxLength?: number; + multiline?: boolean; } export interface Site { @@ -209,6 +224,8 @@ export interface Member { hiddenPrefs?: HiddenPrefs; /** Opt in to list the site events they're going to (or went to) on their profile. Off by default. */ showEvents?: boolean; + /** Niche sites: Browse and Discover also show members outside the niche (e.g. average height). Off by default. */ + showEveryone?: boolean; about: string; fields: Record; status: MemberStatus; @@ -277,7 +294,8 @@ export interface Report { at: string; } -export type ModerationKind = 'photo' | 'message' | 'report' | 'profile'; +/** member: the account as a whole needs a look (answers that don't add up, fetish or "third" wording). refId is the member id. */ +export type ModerationKind = 'photo' | 'message' | 'report' | 'profile' | 'member'; export interface ModerationItem { id: string; kind: ModerationKind; @@ -289,6 +307,10 @@ export interface ModerationItem { createdAt: string; decidedAt?: string; decidedBy?: string; + /** member items: the evidence, one line each (e.g. "Stature: Average height", "Height: 3′ 4″ (102 cm)"). */ + signals?: string[]; + /** member items: a key of the evidence, so a concern marked "Looks fine" isn't raised again for the same answers. */ + evidenceKey?: string; } // ---------------- Events ---------------- @@ -528,6 +550,8 @@ export interface PublicSite { explicitPhotosAllowed: boolean; publicTeasers: boolean; units: Units; + /** Niche sites: Browse shows this checkbox to include members outside the niche. */ + nicheIncludeLabel?: string; /** Present only when the owner turned Google tags on. restricted: sensitive site, no ad personalization or Google signals. */ googleTags?: { ga4Id?: string; adsId?: string; adsJoinLabel?: string; restricted: boolean }; } @@ -539,6 +563,8 @@ export interface SearchFilters { withinMiles?: number | null; withPhoto?: boolean; onlineNow?: boolean; + /** Niche sites: also show members outside the niche. Defaults to the member's showEveryone choice. */ + everyone?: boolean; fields?: Record; // field key -> any of these values sort?: 'best' | 'recent' | 'newest' | 'closest'; page?: number; diff --git a/packages/core/test/niche.test.ts b/packages/core/test/niche.test.ts new file mode 100644 index 0000000..17adf0b --- /dev/null +++ b/packages/core/test/niche.test.ts @@ -0,0 +1,175 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + createLocalAdminApi, createLocalMemberApi, createMemoryPlatform, DEMO_OWNER_EMAIL, memberFlags, outsideNiche, + profileFlags, seedSites, textFlags, upgradeNicheFields, type Site, +} from '../src/index'; + +const sites = () => seedSites(new Date()); +const dal = () => sites().find((s) => s.slug === 'datealittle')!; +const hf = () => sites().find((s) => s.slug === 'hfriends')!; +const codes = (site: Site, fields: Record, gender: any = 'man', about = '') => memberFlags(site, { fields, gender, about }).map((f) => f.code).sort(); + +test('stature vs. height and gender', () => { + const s = dal(); + assert.deepEqual(codes(s, { stature: 'Average height', height: 102 }), ['stature_short'], 'says average, 3\'4"'); + assert.deepEqual(codes(s, { stature: 'Average height', height: 175 }), []); + assert.deepEqual(codes(s, { stature: 'Little person', dwarfism_type: 'Achondroplasia', height: 122 }), []); + assert.deepEqual(codes(s, { stature: 'Little person', dwarfism_type: 'Achondroplasia', height: 178 }), ['stature_tall'], 'claims dwarfism, average height'); + // women and men have their own limits + assert.deepEqual(codes(s, { stature: 'Little person', height: 160 }, 'woman'), ['stature_tall']); + assert.deepEqual(codes(s, { stature: 'Little person', height: 160 }, 'man'), []); + assert.deepEqual(codes(s, { stature: 'Short stature', height: 160 }, 'man'), []); + assert.deepEqual(codes(s, { stature: 'Short stature', height: 180 }, 'man'), ['stature_tall']); + assert.deepEqual(codes(s, { stature: 'Average height', dwarfism_type: 'Achondroplasia', height: 170 }), ['stature_mixed']); + assert.deepEqual(codes(s, { stature: 'Average height', dwarfism_type: 'Prefer not to say', height: 170 }), []); + const f = profileFlags(s, { fields: { stature: 'Average height', height: 102 }, gender: 'woman' })[0]; + assert.ok(f.signals.some((x) => /3′ 4″ \(102 cm\)/.test(x)), f.signals.join(' | ')); + assert.ok(f.signals.includes('Gender: Woman')); + // other sites never get these checks + assert.deepEqual(codes(sites()[0], { stature: 'Average height', height: 102 }), []); +}); + +test('disability answers that do not add up', () => { + const s = hf(); + assert.deepEqual(codes(s, { accessibility: ['No disability'] }), []); + assert.deepEqual(codes(s, { accessibility: ['No disability', 'Wheelchair user'] }), ['disability_mixed']); + const all = s.fields.find((f) => f.key === 'accessibility')!.options!.filter((o) => o !== 'Prefer not to say'); + assert.deepEqual(codes(s, { accessibility: all }), ['disability_all', 'disability_mixed']); + assert.deepEqual(codes(s, { accessibility: ['Wheelchair user', 'Chronic illness', 'Speech or communication'] }), []); +}); + +test('wording: couples looking for a third, fetish and gawker accounts', () => { + const t = (site: Site, text: string) => textFlags(site, text, 'About me').map((f) => f.code); + assert.deepEqual(t(dal(), 'My wife and I are looking for a third to have some fun with'), ['couple_third']); + assert.deepEqual(t(dal(), "We're a fun married couple seeking a woman"), ['couple_third']); + assert.deepEqual(t(dal(), 'Looking for our unicorn!'), ['couple_third']); + assert.deepEqual(t(dal(), "I've always wanted to be with a little woman"), ['fetish']); + assert.deepEqual(t(dal(), 'Dating a midget is on my bucket list'), ['fetish']); + assert.deepEqual(t(hf(), 'Amputee devotee here'), ['fetish']); + // ordinary profiles and members setting boundaries are left alone + assert.deepEqual(t(dal(), 'Third time trying online dating. Our third date ideas: mini golf. I am the third of five kids.'), []); + assert.deepEqual(t(dal(), 'No fetish people please, and not into kink.'), []); + assert.deepEqual(t(hf(), 'Devotees not welcome. No devotees!'), []); + assert.deepEqual(t(dal(), 'Travel is on my bucket list, and I love short road trips.'), []); + const sig = textFlags(dal(), 'Hi there. My husband and I want to meet someone special to join us.', 'About me')[0].signals[0]; + assert.match(sig, /^About me: ".*husband and I want.*"$/); + assert.deepEqual(t(sites()[0], 'My wife and I want a third'), [], 'AfterH has no niche checks'); +}); + +test('who is outside the niche', () => { + assert.equal(outsideNiche(dal(), { fields: { stature: 'Average height' } }), true); + assert.equal(outsideNiche(dal(), { fields: { stature: 'Short stature' } }), false); + assert.equal(outsideNiche(dal(), { fields: { stature: 'Prefer not to say' } }), false); + assert.equal(outsideNiche(dal(), { fields: {} }), false); + assert.equal(outsideNiche(hf(), { fields: { accessibility: ['No disability'] } }), true); + assert.equal(outsideNiche(hf(), { fields: { accessibility: ['No disability', 'Other'] } }), false); + assert.equal(outsideNiche(sites()[0], { fields: { stature: 'Average height' } }), false); +}); + +test('older site definitions are upgraded, keeping options an admin added', () => { + const s = dal(); + s.fields = s.fields.filter((f) => f.key !== 'dwarfism_type'); + s.fields[0] = { key: 'stature', label: 'Stature', type: 'select', options: ['Little person', 'Average height', 'Prefer not to say', 'Tall'], required: true, filterable: true, order: 1 }; + delete s.settings.niche; + assert.equal(upgradeNicheFields(s), true); + assert.deepEqual(s.fields.find((f) => f.key === 'stature')!.options, ['Little person', 'Short stature', 'Average height', 'Prefer not to say', 'Tall']); + assert.ok(s.fields.some((f) => f.key === 'dwarfism_type')); + assert.equal(s.settings.niche!.field, 'stature'); + assert.equal(upgradeNicheFields(s), false, 'second run changes nothing'); + const h = hf(); + h.fields = h.fields.filter((f) => f.key !== 'disability_details'); + h.fields[0] = { ...h.fields[0], options: ['Wheelchair user', 'Prefer not to say'], exclusive: undefined }; + delete h.settings.niche; + assert.equal(upgradeNicheFields(h), true); + assert.ok(h.fields[0].options!.includes('No disability')); + assert.deepEqual(h.fields[0].exclusive, ['No disability', 'Prefer not to say']); + assert.ok(h.fields.some((f) => f.key === 'disability_details')); + assert.equal(upgradeNicheFields(sites()[0]), false); +}); + +async function dalMember(mp: Awaited>, email: string, fields: Record, gender: any = 'man', about = '') { + const api = createLocalMemberApi(mp.platform, 'datealittle', 'web'); + const st = await api.startVerification('email', email); + const { token } = await api.verify(st.challengeId, st.devCode!); + api.setToken(token); + (api as any).token = token; + await api.updateMe({ displayName: email.split('@')[0], birthYear: 1990, gender, seeking: ['woman', 'man'], postal: '80202', fields, about }); + return api; +} + +test('Browse and Discover show the niche by default; members can include everyone', async () => { + const mp = await createMemoryPlatform(); + const avg = await dalMember(mp, 'avg.person@example.com', { stature: 'Average height', height: 178 }, 'woman'); + const viewer = await dalMember(mp, 'lp.viewer@example.com', { stature: 'Little person', height: 120 }); + const avgId = (await avg.me()).member.id; + const wide = { withinMiles: null, withPhoto: false, ageMin: 18, ageMax: 99, pageSize: 48 } as const; + const discover = async () => { + const p = mp.platform as any; + return p.discover(await p.memberCtx(await p.resolveSite('datealittle'), (viewer as any).token, 'web'), 500) as Promise<{ id: string }[]>; + }; + const all = async (everyone?: boolean) => { + const ids: string[] = []; + for (let page = 1; ; page++) { + const r = await viewer.search({ ...wide, everyone, page }); + ids.push(...r.people.map((p) => p.id)); + if (page * r.pageSize >= r.total) return ids; + } + }; + assert.ok(!(await all()).includes(avgId), 'average height hidden by default'); + assert.ok((await all(true)).includes(avgId), 'shown when including everyone'); + assert.ok(!(await discover()).some((c) => c.id === avgId)); + await viewer.updateMe({ showEveryone: true }); + assert.ok((await all()).includes(avgId), 'remembered choice is the default'); + assert.ok((await discover()).some((c) => c.id === avgId)); + // an average-height member browsing sees little people as usual + assert.ok((await avg.search({ ...wide })).total > 0); +}); + +test('suspicious accounts land in review once; Looks fine sticks; Suspend is the admin\'s call', async () => { + const mp = await createMemoryPlatform(); + const sus = await dalMember(mp, 'sus@example.com', { stature: 'Average height', height: 102 }); + const id = (await sus.me()).member.id; + const admin = createLocalAdminApi(mp.platform); + const st = await admin.start(DEMO_OWNER_EMAIL); + admin.setToken((await admin.verify(st.challengeId, st.devCode!)).token); + const mine = async () => (await admin.moderation('site_datealittle', 'pending')).filter((i) => i.kind === 'member' && i.memberId === id); + let items = await mine(); + assert.equal(items.length, 1); + assert.equal(items[0].reasons[0], 'Says average height, but is very short'); + assert.ok(items[0].signals!.some((s) => s.startsWith('Height: 3′ 4″'))); + assert.equal((await sus.me()).member.status, 'active', 'flagging never suspends'); + + await sus.updateMe({ about: 'Hello!' }); // a second save doesn't duplicate it + assert.equal((await mine()).length, 1); + await admin.decide('site_datealittle', items[0].id, 'approve'); + assert.equal((await mine()).length, 0); + const again = await admin.runNicheChecks('site_datealittle'); + assert.ok(again.checked > 1); + assert.equal((await mine()).length, 0, 'marked fine: same answers are not raised again'); + + // messages: wording flags the sender for review without holding the message + const other = await dalMember(mp, 'lp.other@example.com', { stature: 'Little person', height: 115 }, 'woman'); + const otherId = (await other.me()).member.id; + const conv = await sus.send(otherId, 'My wife and I are looking for a third, are you interested?'); + assert.equal(conv.messages.at(-1)!.held ?? false, false); + items = await mine(); + assert.equal(items.length, 1); + assert.equal(items[0].reasons[0], 'May be a couple looking for a "third"'); + assert.match(items[0].signals![0], /^Message to lp\.other: /); + assert.equal(items[0].signals!.length, 1, 'two matching phrases in one message give one evidence line'); + await admin.decide('site_datealittle', items[0].id, 'reject'); + const view = await admin.memberProfile('site_datealittle', id); + assert.equal(view.status, 'suspended'); +}); + +test('profile edits accept heights under 3 feet and longer disability details', async () => { + const mp = await createMemoryPlatform(); + const api = await dalMember(mp, 'short@example.com', { stature: 'Little person', dwarfism_type: 'Primordial dwarfism (MOPD, Seckel)', height: 74 }); + assert.equal((await api.me()).member.fields.height, 74); + const h = createLocalMemberApi(mp.platform, 'hfriends', 'web'); + const st = await h.startVerification('email', 'hf@example.com'); + h.setToken((await h.verify(st.challengeId, st.devCode!)).token); + await h.updateMe({ displayName: 'Robin', birthYear: 1985, gender: 'woman', seeking: ['man'], postal: '80202', fields: { accessibility: ['Wheelchair user'], disability_details: 'x'.repeat(450) } }); + await assert.rejects(h.updateMe({ fields: { accessibility: ['No disability', 'Wheelchair user'] } }), /can't be combined/); +});