import { languageName } from '../../../shared/languages.ts' import { FILTER_META, filterConfig, type Doc, type Punishment, type Targeting } from '../../../shared/schemas.ts' import type { ChannelConfig } from './config.ts' import { detectForeignLanguage } from './language.ts' import { checkConditions, type LiveConditionInput, type UserRoles } from './roles.ts' import { capsPercent, countEmoji, extractHosts, hostAllowed, maxCombining, repetition, similarity, symbolsPercent, visualLines, } from './text.ts' export interface RecentMessage { did: string text: string at: number } export interface ModInput { text: string did: string handle: string displayName: string replyRoot: string | null facetUris: string[] /** The sender's earlier messages, oldest first, not including this one. */ userRecent: RecentMessage[] /** Everyone's earlier messages, oldest first, not including this one. */ channelRecent: RecentMessage[] threadReplies: (rootUri: string) => number prefix: string malwareHosts: ReadonlySet live: LiveConditionInput roles: UserRoles | null now: number } export interface ModVerdict { source: 'blocked_term' | 'filter' id: string name: string punishment: Punishment /** A short explanation for the audit log, e.g. "72% caps". */ detail: string } function targetText(targeting: Targeting, input: ModInput, normalize: (s: string) => string, useLookalikes: boolean): string[] { const n = useLookalikes ? normalize : (s: string) => s const name = [input.handle, input.displayName].filter(Boolean).join(' ') switch (targeting) { case 'message': return [n(input.text)] case 'username': return [n(name)] case 'both': return [n(input.text), n(name)] } } function checkBlockedTerms(cfg: ChannelConfig, input: ModInput): ModVerdict | null { for (const { doc, matcher } of cfg.blockedTerms) { const t = doc.data if (!t.enabled) continue if (checkConditions(t.conditions, input.roles, input.live)) continue let texts = targetText(t.targeting, input, cfg.normalize, t.useLookalikes) if (t.multiLine > 1 && t.targeting !== 'username') { const previous = input.userRecent.slice(-(t.multiLine - 1)).map((m) => m.text) const joined = [...previous, input.text].join('') texts = [...texts, t.useLookalikes ? cfg.normalize(joined) : joined] } for (const text of texts) { const m = matcher(text) if (m) return { source: 'blocked_term', id: doc.id, name: t.phrase.text, punishment: t.punishment, detail: `matched “${m[0].trim().slice(0, 60)}”` } } } return null } function checkFilter(filter: Doc<'filter'>, input: ModInput, cfg: ChannelConfig): string | null { const text = input.text switch (filter.data.type) { case 'caps': { const c = filterConfig('caps', filter.data.config) const letters = text.replace(/[^\p{L}]/gu, '') if (letters.length < c.minLength) return null const pct = capsPercent(text) return pct > c.maxPercent ? `${Math.round(pct)}% caps` : null } case 'commands': { const c = filterConfig('commands', filter.data.config) const trimmed = text.trim() const prefix = c.prefixes.find((p) => p && trimmed.startsWith(p)) if (!prefix) return null const name = trimmed.slice(prefix.length).split(/\s+/)[0]?.toLowerCase() if (!name) return null if (c.allowOwnCommands && prefix === input.prefix && (cfg.commandsByTrigger.has(name) || cfg.defaultsByTrigger.has(name))) return null return `command “${prefix}${name}”` } case 'emoji': { const c = filterConfig('emoji', filter.data.config) const n = countEmoji(text) return n > c.maxEmoji ? `${n} emoji` : null } case 'language': { const language = detectForeignLanguage(text, filterConfig('language', filter.data.config)) return language ? `written in ${languageName(language)}` : null } case 'length': { const c = filterConfig('length', filter.data.config) const n = [...text].length return n > c.maxLength ? `${n} characters` : null } case 'links': { const c = filterConfig('links', filter.data.config) const hosts = extractHosts(text, input.facetUris) const bad = hosts.filter((h) => !hostAllowed(h, c.allowedDomains)) if (!bad.length) return null return c.blockAll ? `link to ${bad[0]}` : null } case 'malware': { const hosts = extractHosts(text, input.facetUris) const bad = hosts.find((h) => input.malwareHosts.has(h)) return bad ? `known malicious link ${bad}` : null } case 'height': { const c = filterConfig('height', filter.data.config) const lines = visualLines(text, c.charsPerLine) return lines > c.maxLines ? `${lines} lines tall` : null } case 'oneman': { const c = filterConfig('oneman', filter.data.config) const since = input.now - c.seconds * 1000 const similar = input.userRecent.filter((m) => m.at >= since && similarity(m.text, text) >= c.similarity) return similar.length + 1 >= c.messages ? `${similar.length + 1} similar messages in ${c.seconds}s` : null } case 'repetition': { const c = filterConfig('repetition', filter.data.config) if ([...text].length < c.minLength) return null const r = repetition(text) if (r.maxWordRepeats > c.maxWordRepeats) return `a word repeated ${r.maxWordRepeats} times` if (r.maxCharRun > c.maxCharRepeats) return `a character repeated ${r.maxCharRun} times` return null } case 'symbols': { const c = filterConfig('symbols', filter.data.config) if ([...text.replace(/\s/g, '')].length < c.minLength) return null const pct = symbolsPercent(text) return pct > c.maxPercent ? `${Math.round(pct)}% symbols` : null } case 'thread': { const c = filterConfig('thread', filter.data.config) if (!input.replyRoot) return null const n = input.threadReplies(input.replyRoot) + 1 return n > c.maxReplies ? `reply #${n} in one thread` : null } case 'unique': { const c = filterConfig('unique', filter.data.config) const since = input.now - c.seconds * 1000 const recent = input.channelRecent.filter((m) => m.at >= since).slice(-c.lookback) const dupe = recent.find((m) => similarity(m.text, text) >= c.similarity) return dupe ? 'not unique enough' : null } case 'zalgo': { const c = filterConfig('zalgo', filter.data.config) const n = maxCombining(text) return n > c.maxCombining ? `${n} stacked marks` : null } } } function checkFilters(cfg: ChannelConfig, input: ModInput): ModVerdict | null { for (const f of cfg.filters) { if (!f.data.enabled) continue if (checkConditions(f.data.conditions, input.roles, input.live)) continue const detail = checkFilter(f, input, cfg) if (detail) return { source: 'filter', id: f.id, name: f.data.name || FILTER_META[f.data.type].label, punishment: f.data.punishment, detail } } return null } /** The first blocked term or spam filter this message trips (blocked terms first, pinned ones before others). */ export function evaluateModeration(cfg: ChannelConfig, input: ModInput): ModVerdict | null { return checkBlockedTerms(cfg, input) ?? checkFilters(cfg, input) } /** Timeout length for an offence, doubling (by the multiplier) for repeat offenders up to the max. */ export function escalatedTimeout(p: Punishment, priorOffences: number): number { if (!p.repeatOffenders.enabled || priorOffences <= 0) return Math.min(p.baseTimeout, Math.max(p.maxTimeout, p.baseTimeout)) const scaled = p.baseTimeout * p.repeatOffenders.multiplier ** priorOffences return Math.round(Math.min(scaled, Math.max(p.maxTimeout, p.baseTimeout))) }