-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabuseDetection.ts
More file actions
144 lines (125 loc) · 4.6 KB
/
Copy pathabuseDetection.ts
File metadata and controls
144 lines (125 loc) · 4.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import type { SpacetimeAdminConfig } from './config.js';
import { createSpacetimeSqlQuery, numberValue, sqlString, stringValue } from './spacetimeSql.js';
export interface PairActivity {
opponentAccountId: string;
matchCount: number;
totalAwardedPoints: number;
}
export interface AbuseSignals {
accountId: string;
recentMatches: Array<{
matchId: string;
opponentAccountId: string;
outcome: string;
completedRounds: number;
awardedPoints: number;
settledAt: string;
}>;
windowHours?: number;
}
export interface RiskAssessment {
riskScore: number;
holdForReview: boolean;
signals: string[];
}
export interface RiskConfig {
holdThreshold?: number;
pairDailyMatchLimit?: number;
minAvgCompletedRounds?: number;
maxForfeitRate?: number;
maxWinRate?: number;
}
const DEFAULT_CONFIG: Required<RiskConfig> = {
holdThreshold: 30,
pairDailyMatchLimit: 10,
minAvgCompletedRounds: 1,
maxForfeitRate: 0.4,
maxWinRate: 0.95,
};
export function assessRisk(signals: AbuseSignals, config?: RiskConfig): RiskAssessment {
const cfg = { ...DEFAULT_CONFIG, ...config };
const { accountId, recentMatches } = signals;
let riskScore = 0;
const flaggedSignals: string[] = [];
if (recentMatches.length === 0) return { riskScore: 0, holdForReview: false, signals: [] };
// Self-match: playing against own account
const selfMatch = recentMatches.find(m => m.opponentAccountId === accountId);
if (selfMatch) {
riskScore += 100;
flaggedSignals.push('self_match_detected');
}
// Repeated pair farming: too many matches vs same opponent in window
const pairCounts = new Map<string, number>();
for (const m of recentMatches) {
pairCounts.set(m.opponentAccountId, (pairCounts.get(m.opponentAccountId) ?? 0) + 1);
}
for (const [opp, count] of pairCounts) {
if (count > cfg.pairDailyMatchLimit) {
riskScore += 20;
flaggedSignals.push(`repeated_pair:${opp}:${count}`);
}
}
// Rapid forfeits: high forfeit/timeout rate
const forfeitCount = recentMatches.filter(m =>
m.outcome === 'forfeit_loss' || m.outcome === 'timeout_loss' || m.outcome === 'forfeit_win' || m.outcome === 'timeout_win'
).length;
const forfeitRate = forfeitCount / recentMatches.length;
if (forfeitRate > cfg.maxForfeitRate) {
riskScore += 30;
flaggedSignals.push(`high_forfeit_rate:${Math.round(forfeitRate * 100)}%`);
}
// Abnormal win rate: suspiciously high
const winCount = recentMatches.filter(m =>
m.outcome === 'win' || m.outcome === 'forfeit_win' || m.outcome === 'timeout_win' || m.outcome === 'disconnect_win'
).length;
const winRate = winCount / recentMatches.length;
if (recentMatches.length >= 5 && winRate > cfg.maxWinRate) {
riskScore += 15;
flaggedSignals.push(`abnormal_win_rate:${Math.round(winRate * 100)}%`);
}
// Very short matches: rounds < minimum (possible scripted matches)
const avgRounds = recentMatches.reduce((s, m) => s + m.completedRounds, 0) / recentMatches.length;
if (avgRounds < cfg.minAvgCompletedRounds) {
riskScore += 20;
flaggedSignals.push(`low_avg_rounds:${avgRounds.toFixed(1)}`);
}
return {
riskScore,
holdForReview: riskScore >= cfg.holdThreshold,
signals: flaggedSignals,
};
}
export interface AbuseDetectionStore {
evaluateAccount(accountId: string, campaignId: string, windowHours?: number): Promise<RiskAssessment>;
}
interface RewardPointEventRow extends Record<string, unknown> {
match_id: unknown;
opponent_account_id: unknown;
outcome: unknown;
awarded_points: unknown;
settled_at_micros: unknown;
}
export function createAbuseDetectionStore(
config: SpacetimeAdminConfig,
fetchImpl: typeof fetch = fetch,
riskConfig?: RiskConfig,
): AbuseDetectionStore {
const sql = createSpacetimeSqlQuery(config, fetchImpl);
return {
async evaluateAccount(accountId, campaignId, windowHours = 24) {
const windowStart = BigInt(Date.now() - windowHours * 3_600_000) * 1000n;
const rows = await sql(
`SELECT * FROM reward_point_event WHERE account_id = ${sqlString(accountId)} AND campaign_id = ${sqlString(campaignId)} AND settled_at_micros >= ${windowStart}`,
);
const recentMatches = (rows as RewardPointEventRow[]).map(r => ({
matchId: stringValue(r.match_id),
opponentAccountId: stringValue(r.opponent_account_id),
outcome: stringValue(r.outcome),
completedRounds: 1,
awardedPoints: numberValue(r.awarded_points),
settledAt: new Date(Math.floor(numberValue(r.settled_at_micros) / 1000)).toISOString(),
}));
return assessRisk({ accountId, recentMatches, windowHours }, riskConfig);
},
};
}