-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmlAnomalyDetector.ts
More file actions
239 lines (212 loc) · 6.82 KB
/
mlAnomalyDetector.ts
File metadata and controls
239 lines (212 loc) · 6.82 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Withdrawal anomaly scoring for crypto gateway risk decisions.
import type { Collection } from "mongodb";
import type { Logger } from "pino";
import type { MongoDependencies } from "../../shared/storage/mongo.js";
import {
mongoCollections,
type CryptoWithdrawalDocument
} from "../../shared/storage/mongoSchemas.js";
export type WithdrawalAnomalyInput = {
userId: string;
currency: string;
amount: number;
destinationAddress: string;
requestedAt: Date;
};
export type WithdrawalAnomalyResult = {
score: number;
reasons: string[];
historyCount: number;
};
export type WithdrawalAnomalyConfig = {
historyLimit: number;
reviewThreshold: number;
rejectThreshold: number;
};
type WithdrawalProfile = {
userId: string;
currency: string;
avgAmount: number;
stdAmount: number;
avgFrequencyHours: number | null;
timeOfDayPattern: number[];
knownAddresses: Set<string>;
lastRequestedAt: Date | null;
historyCount: number;
computedAt: Date;
};
const profileTtlMs = 5 * 60 * 1000;
export function createMlAnomalyDetector(
mongo: MongoDependencies,
config: WithdrawalAnomalyConfig,
logger?: Logger
) {
const withdrawals = mongo.db.collection<CryptoWithdrawalDocument>(
mongoCollections.cryptoWithdrawals
);
const profiles = new Map<string, WithdrawalProfile>();
async function evaluate(input: WithdrawalAnomalyInput): Promise<WithdrawalAnomalyResult> {
const profile = await loadProfile(withdrawals, profiles, input, config, logger);
if (profile.historyCount === 0) {
return { score: 0, reasons: [], historyCount: 0 };
}
const reasons: string[] = [];
let score = 0;
const deviation = computeAmountDeviation(input.amount, profile.avgAmount, profile.stdAmount);
if (deviation > 3) {
score += 40;
reasons.push(`amount_deviation:${deviation.toFixed(2)}σ`);
}
if (profile.knownAddresses.size > 0 && !profile.knownAddresses.has(input.destinationAddress)) {
score += 25;
reasons.push("new_destination");
}
if (profile.avgFrequencyHours !== null && profile.lastRequestedAt) {
const hoursSince =
(input.requestedAt.getTime() - profile.lastRequestedAt.getTime()) / 3600000;
if (hoursSince >= 0 && hoursSince < profile.avgFrequencyHours * 0.2) {
score += 30;
reasons.push(`high_frequency:${hoursSince.toFixed(1)}h`);
}
}
if (profile.historyCount >= 10) {
const hour = input.requestedAt.getHours();
const typical = profile.timeOfDayPattern[hour] ?? 0;
if (typical < 0.08) {
score += 15;
reasons.push(`unusual_time:${hour}`);
}
}
const recentCount = await countRecentWithdrawals(withdrawals, input.userId, input.currency);
if (recentCount >= 3) {
score += 20;
reasons.push(`rapid_succession:${recentCount}`);
}
return { score, reasons, historyCount: profile.historyCount };
}
return {
evaluate,
reviewThreshold: config.reviewThreshold,
rejectThreshold: config.rejectThreshold
};
}
async function loadProfile(
withdrawals: Collection<CryptoWithdrawalDocument>,
profiles: Map<string, WithdrawalProfile>,
input: WithdrawalAnomalyInput,
config: WithdrawalAnomalyConfig,
logger?: Logger
): Promise<WithdrawalProfile> {
const key = `${input.userId}:${input.currency}`;
const cached = profiles.get(key);
if (cached && Date.now() - cached.computedAt.getTime() <= profileTtlMs) {
return cached;
}
const history = await withdrawals
.find({
userId: input.userId,
currency: input.currency,
status: "confirmed"
})
.sort({ confirmedAt: -1, requestedAt: -1 })
.limit(Math.max(1, Math.floor(config.historyLimit)))
.toArray();
const profile = buildProfile(input.userId, input.currency, history);
profiles.set(key, profile);
if (logger && profile.historyCount === 0) {
logger.info(
{ userId: input.userId, currency: input.currency },
"No withdrawal history for anomaly scoring"
);
}
return profile;
}
function buildProfile(
userId: string,
currency: string,
history: CryptoWithdrawalDocument[]
): WithdrawalProfile {
const amounts = history
.map((entry) => entry.amount)
.filter((value) => Number.isFinite(value) && value > 0);
const historyCount = history.length;
const avgAmount = amounts.length > 0 ? mean(amounts) : 0;
const stdAmount = amounts.length > 1 ? stddev(amounts, avgAmount) : 0;
const ordered = [...history].sort((a, b) => {
const timeA = a.requestedAt?.getTime() ?? 0;
const timeB = b.requestedAt?.getTime() ?? 0;
return timeB - timeA;
});
const timestamps = ordered
.map((entry) => entry.requestedAt)
.filter((value): value is Date => value instanceof Date);
const intervals = [];
for (let index = 1; index < timestamps.length; index += 1) {
const prev = timestamps[index - 1];
const next = timestamps[index];
if (!prev || !next) {
continue;
}
intervals.push((prev.getTime() - next.getTime()) / 3600000);
}
const avgFrequencyHours = intervals.length > 0 ? mean(intervals) : null;
const timeOfDayPattern = new Array(24).fill(0);
for (const entry of history) {
const date = entry.requestedAt ?? entry.confirmedAt;
if (!date) {
continue;
}
const hour = date.getHours();
timeOfDayPattern[hour] += 1;
}
const total = timeOfDayPattern.reduce((sum, value) => sum + value, 0);
const normalized =
total > 0 ? timeOfDayPattern.map((value) => value / total) : timeOfDayPattern;
const knownAddresses = new Set(
history.map((entry) => entry.destinationAddress).filter((value) => value)
);
const lastRequestedAt = timestamps[0] ?? null;
return {
userId,
currency,
avgAmount,
stdAmount,
avgFrequencyHours,
timeOfDayPattern: normalized,
knownAddresses,
lastRequestedAt,
historyCount,
computedAt: new Date()
};
}
function computeAmountDeviation(amount: number, avg: number, std: number): number {
if (!Number.isFinite(amount) || amount <= 0 || !Number.isFinite(avg)) {
return 0;
}
const sigma = std > 0 ? std : Math.max(1e-9, avg * 0.1);
return Math.abs(amount - avg) / sigma;
}
async function countRecentWithdrawals(
withdrawals: Collection<CryptoWithdrawalDocument>,
userId: string,
currency: string
): Promise<number> {
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
return withdrawals.countDocuments({
userId,
currency,
requestedAt: { $gte: oneHourAgo },
status: { $in: ["requested", "authorized", "broadcasted", "confirmed"] }
});
}
function mean(values: number[]): number {
if (values.length === 0) {
return 0;
}
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function stddev(values: number[], avg: number): number {
const variance =
values.reduce((sum, value) => sum + Math.pow(value - avg, 2), 0) / values.length;
return Math.sqrt(variance);
}