Repository navigation
Expand file tree
/
Copy pathaml.ts
More file actions
839 lines (803 loc) · 41.9 KB
/
Copy pathaml.ts
File metadata and controls
839 lines (803 loc) · 41.9 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
import crypto from "crypto";
import { z } from "zod";
import { router, protectedProcedure, writeProcedure, adminProcedure } from "./_core/trpc";
import { ENV } from "./_core/env";
import { getDb } from "./db";
import { publishAmlAlert, publishTransactionEvent } from "./dapr";
import { withCache, invalidateCache, TTL } from "./cache";
import { permifyCheck, permifyWriteRelationship } from "./permify";
import { startAmlWorkflow } from "./temporal";
import { writeLakehouseEvent } from "./lakehouse";
import { fluvioPublishAmlEvent, fluvioPublishTransactionEvent } from "./fluvio";
import {
transactions, amlRules, amlAlerts, swiftMessages, sepaPayments, travelRuleRecords, cases, alertRules, webhooks, velocityBlocks,
} from "../drizzle/schema";
import { eq, desc, and, gte, lte, like, or, sql, count, sum } from "drizzle-orm";
// ─── Webhook Retry Helper ─────────────────────────────────────────────────────
/**
* Deliver a webhook payload with exponential backoff retry.
* Attempts: 1, 2, 4, 8, 16 seconds (5 attempts, max ~31s total).
* Adds ±20% jitter to each delay to prevent thundering herd.
*/
async function deliverWithRetry(
url: string,
headers: Record<string, string>,
body: string,
maxAttempts = 5,
): Promise<{ ok: boolean; status: number; attempts: number }> {
let lastStatus = 0;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", ...headers },
body,
signal: AbortSignal.timeout(8_000),
});
if (res.ok) return { ok: true, status: res.status, attempts: attempt };
lastStatus = res.status;
// 4xx errors are permanent — do not retry
if (res.status >= 400 && res.status < 500) break;
} catch {
lastStatus = 0;
}
if (attempt < maxAttempts) {
const baseMs = (2 ** (attempt - 1)) * 1_000; // 1s, 2s, 4s, 8s
const jitter = 0; // deterministic: no random jitter in production
await new Promise(r => setTimeout(r, Math.max(100, baseMs + jitter)));
}
}
return { ok: false, status: lastStatus, attempts: maxAttempts };
}
// ─── AML Webhook Fan-out ──────────────────────────────────────────────────────
/**
* Dispatch an AML alert event to all active tenant webhooks subscribed to
* "aml.alert" events. Non-blocking — failures are logged but do not affect
* the main transaction flow. Uses exponential backoff retry (5 attempts).
*/
async function dispatchAmlWebhook(payload: {
tenantId: number;
event: string;
riskLevel: string;
title: string;
transactionId: number;
amount: number;
currency: string;
originatorName: string;
beneficiaryName: string;
flags: string[];
timestamp: string;
}): Promise<void> {
try {
const db = await getDb();
if (!db) return;
// Find all active webhooks subscribed to aml.alert events
const activeWebhooks = await db.select().from(webhooks)
.where(and(eq(webhooks.status, "active"), eq(webhooks.tenantId, payload.tenantId)));
const amlWebhooks = activeWebhooks.filter(wh => {
const events = (wh.events ?? []) as string[];
return events.length === 0 || events.includes("aml.alert") || events.includes("*");
});
if (amlWebhooks.length === 0) return;
const body = JSON.stringify(payload);
await Promise.allSettled(amlWebhooks.map(async (wh) => {
const sig = `sha256=${crypto.createHmac("sha256", wh.secret ?? "").update(body).digest("hex")}`;
const result = await deliverWithRetry(
wh.url,
{ "X-BIS-Signature": sig, "X-BIS-Event": payload.event },
body,
);
if (result.ok) {
await db.update(webhooks).set({ lastDeliveredAt: new Date(), failureCount: 0 }).where(eq(webhooks.id, wh.id)).catch(() => {});
} else {
const newFailCount = (wh.failureCount ?? 0) + result.attempts;
await db.update(webhooks).set({ failureCount: newFailCount }).where(eq(webhooks.id, wh.id)).catch(() => {});
console.warn(`[AML Webhook] Delivery failed after ${result.attempts} attempts for webhook ${wh.id} (${wh.url}) — status ${result.status}`);
}
}));
} catch (err) {
console.warn("[AML Webhook] Fan-out error:", err);
}
}
// ─── AML Auto-Escalation ─────────────────────────────────────────────────────
/**
* When an AML alert is created and the triggering rule has autoEscalate=true,
* automatically create a Case in the case management system.
*/
async function autoEscalateToCase(db: NonNullable<Awaited<ReturnType<typeof getDb>>>, alert: {
id: number;
riskLevel: string;
title: string;
description: string;
alertRef?: string | null;
transactionId?: number | null;
investigationId?: number | null;
}, createdBy: number): Promise<void> {
try {
const caseRef = `CASE-AML-${Date.now().toString(36).toUpperCase()}-${crypto.randomUUID().replace(/-/g,'').slice(0,5).toUpperCase()}`;
const priority = alert.riskLevel === "critical" ? "critical" : alert.riskLevel === "high" ? "high" : "medium";
await db.insert(cases).values({
ref: caseRef,
title: `[AUTO-ESCALATED] ${alert.title}`,
type: "aml",
status: "open",
priority: priority as any,
summary: `Automatically escalated from AML alert ${alert.alertRef ?? `ALT-\${String(alert.id).padStart(6, "0")}`}. ${alert.description}`,
legalBasis: "MLPA 2011 s.6 — Suspicious Transaction Reporting",
regulatoryFramework: "NFIU/CBN AML/CFT Framework 2022",
riskScore: alert.riskLevel === "critical" ? 90 : alert.riskLevel === "high" ? 70 : 50,
createdBy,
investigationRefs: alert.investigationId ? [String(alert.investigationId)] : [],
});
} catch (err) {
// Non-blocking: log but don't fail the alert creation
console.error("[AML AutoEscalate] Failed to create case:", err);
}
}
// ─── AML Engine (Rust microservice, port 8095) ────────────────────────────────
const AML_ENGINE_URL = ENV.bisAmlEngineUrl;
async function callAmlEngine(path: string, body: unknown): Promise<unknown> {
try {
const res = await fetch(`${AML_ENGINE_URL}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(8_000),
});
if (!res.ok) throw new Error(`AML engine HTTP ${res.status}`);
return await res.json();
} catch {
return null; // graceful degradation — engine offline
}
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function txRef(): string {
return `TXN-${Date.now().toString(36).toUpperCase()}-${crypto.randomUUID().replace(/-/g,'').slice(0,6).toUpperCase()}`;
}
function amlAlertRef(): string {
return `AML-${Date.now().toString(36).toUpperCase()}-${crypto.randomUUID().replace(/-/g,'').slice(0,5).toUpperCase()}`;
}
function uetrGen(): string {
const hex = () => crypto.randomUUID().replace(/-/g,'').slice(0,8);
return `${hex()}-${hex().slice(0, 4)}-4${hex().slice(0, 3)}-${hex().slice(0, 4)}-${hex()}${hex().slice(0, 4)}`;
}
function requireTenantId(ctx: { tenantId?: number | null }): number {
if (ctx.tenantId === null || ctx.tenantId === undefined) {
throw new Error("Tenant context is required for financial operations");
}
return ctx.tenantId;
}
function assertLegalTransition(
current: string,
next: string,
transitions: Record<string, readonly string[]>,
label: string,
): void {
if (!transitions[current]?.includes(next)) {
throw new Error(`Illegal ${label} transition: ${current} -> ${next}`);
}
}
function scoreTransaction(tx: {
amount: number; currency: string; originatorCountry: string; beneficiaryCountry: string;
type: string; narration?: string | null;
}): { score: number; flags: string[] } {
const flags: string[] = [];
let score = 0;
const HIGH_RISK = ["AF", "BY", "CF", "CG", "CU", "ER", "IR", "KP", "LY", "ML", "MM", "NI", "RU", "SO", "SS", "SY", "VE", "YE", "ZW"];
if (HIGH_RISK.includes(tx.originatorCountry)) { flags.push("high_risk_originator_country"); score += 35; }
if (HIGH_RISK.includes(tx.beneficiaryCountry)) { flags.push("high_risk_beneficiary_country"); score += 35; }
if (tx.currency === "NGN" && tx.amount >= 4_900_000 && tx.amount < 5_000_000) { flags.push("potential_structuring"); score += 40; }
if (tx.currency === "NGN" && tx.amount >= 5_000_000) { flags.push("large_cash_transaction"); score += 20; }
if (tx.type === "cash_deposit" || tx.type === "cash_withdrawal") { flags.push("cash_transaction"); score += 10; }
if (tx.narration && /shell|offshore|nominee|bearer|crypto|bitcoin/i.test(tx.narration)) { flags.push("suspicious_narration"); score += 25; }
if (tx.type === "fx_conversion" && tx.amount > 50000) { flags.push("large_fx_conversion"); score += 15; }
return { score: Math.min(score, 100), flags };
}
// ─── Router ───────────────────────────────────────────────────────────────────
export const amlRouter = router({
transactions: router({
list: protectedProcedure
.input(z.object({
limit: z.number().min(1).max(200).default(50),
offset: z.number().min(0).default(0),
status: z.string().optional(),
riskLevel: z.string().optional(),
type: z.string().optional(),
search: z.string().optional(),
dateFrom: z.string().optional(),
dateTo: z.string().optional(),
minAmount: z.number().optional(),
maxAmount: z.number().optional(),
}))
.query(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const conditions = [];
if (ctx.tenantId !== null) conditions.push(eq(transactions.tenantId, ctx.tenantId));
if (input.status) conditions.push(eq(transactions.status, input.status as any));
if (input.riskLevel) conditions.push(eq(transactions.amlRiskLevel, input.riskLevel as any));
if (input.type) conditions.push(eq(transactions.type, input.type as any));
if (input.search) {
conditions.push(or(
like(transactions.originatorName, `%${input.search}%`),
like(transactions.beneficiaryName, `%${input.search}%`),
like(transactions.txRef, `%${input.search}%`),
)!);
}
if (input.dateFrom) conditions.push(gte(transactions.createdAt, new Date(input.dateFrom)));
if (input.dateTo) conditions.push(lte(transactions.createdAt, new Date(input.dateTo)));
if (input.minAmount !== undefined) conditions.push(gte(transactions.amount, input.minAmount));
if (input.maxAmount !== undefined) conditions.push(lte(transactions.amount, input.maxAmount));
const where = conditions.length > 0 ? and(...conditions) : undefined;
const [rows, [{ total }]] = await Promise.all([
db.select().from(transactions).where(where).orderBy(desc(transactions.createdAt)).limit(input.limit).offset(input.offset),
db.select({ total: count() }).from(transactions).where(where),
]);
return { items: rows, total };
}),
get: protectedProcedure.input(z.object({ id: z.number() })).query(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const where = ctx.tenantId !== null
? and(eq(transactions.id, input.id), eq(transactions.tenantId, ctx.tenantId))
: eq(transactions.id, input.id);
const [row] = await db.select().from(transactions).where(where);
return row ?? null;
}),
create: writeProcedure
.input(z.object({
type: z.enum(["wire_transfer", "cash_deposit", "cash_withdrawal", "cheque", "rtgs", "nip",
"swift_mt103", "swift_mt202", "sepa_credit", "sepa_debit", "internal_transfer",
"trade_settlement", "fx_conversion", "card_payment", "mobile_money"]),
amount: z.number().positive(),
currency: z.string().length(3).default("NGN"),
originatorName: z.string().min(2),
originatorAccount: z.string().optional(),
originatorBank: z.string().optional(),
originatorCountry: z.string().length(2).default("NG"),
beneficiaryName: z.string().min(2),
beneficiaryAccount: z.string().optional(),
beneficiaryBank: z.string().optional(),
beneficiaryCountry: z.string().length(2).default("NG"),
purposeCode: z.string().optional(),
narration: z.string().optional(),
valueDate: z.string().optional(),
investigationId: z.number().optional(),
}))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
const { score, flags } = scoreTransaction({
amount: input.amount, currency: input.currency,
originatorCountry: input.originatorCountry, beneficiaryCountry: input.beneficiaryCountry,
type: input.type, narration: input.narration,
});
const riskLevel = score >= 70 ? "critical" : score >= 50 ? "high" : score >= 25 ? "medium" : "low";
const status = score >= 70 ? "flagged" : "completed";
const [tx] = await db.insert(transactions).values({
tenantId,
txRef: txRef(), type: input.type, status: status as any,
amount: input.amount, currency: input.currency,
amountUsd: input.currency === "USD" ? input.amount : input.currency === "NGN" ? input.amount / 1600 : undefined,
originatorName: input.originatorName, originatorAccount: input.originatorAccount,
originatorBank: input.originatorBank, originatorCountry: input.originatorCountry,
beneficiaryName: input.beneficiaryName, beneficiaryAccount: input.beneficiaryAccount,
beneficiaryBank: input.beneficiaryBank, beneficiaryCountry: input.beneficiaryCountry,
purposeCode: input.purposeCode, narration: input.narration,
amlRiskLevel: riskLevel as any, amlScore: score, amlFlags: flags,
flaggedAt: score >= 50 ? new Date() : undefined,
flaggedBy: score >= 50 ? ctx.user.id : undefined,
investigationId: input.investigationId,
valueDate: input.valueDate ? new Date(input.valueDate) : new Date(),
}).returning();
if (score >= 50 && flags.length > 0) {
const [newAlert] = await db.insert(amlAlerts).values({ tenantId, alertRef: amlAlertRef(), transactionId: tx.id, status: "open",
riskLevel: riskLevel as any,
title: `${riskLevel.toUpperCase()} Risk: ${input.originatorName} → ${input.beneficiaryName}`,
description: `Transaction ${tx.txRef} triggered: ${flags.join(", ")}. Amount: ${input.currency} ${input.amount.toLocaleString()}`,
triggeredValue: input.amount, investigationId: input.investigationId,
}).returning();
// Auto-escalation: if risk is critical or high, check enabled alertRules with autoEscalate=true
if (score >= 70) {
const autoEscRules = await db.select().from(alertRules).where(
and(eq(alertRules.enabled, true), eq(alertRules.autoEscalate, true))
);
if (autoEscRules.length > 0) {
await autoEscalateToCase(db, {
id: newAlert.id,
riskLevel: riskLevel,
title: newAlert.title ?? `AML Alert ${newAlert.alertRef ?? `ALT-\${String(newAlert.id).padStart(6, "0")}`}`,
description: newAlert.description ?? ``,
transactionId: tx.id,
investigationId: input.investigationId,
}, ctx.user.id);
}
}
// Dapr pub/sub: publish AML alert event (non-blocking)
publishAmlAlert({alertId: 0,
alertType: riskLevel,
riskScore: score,
transactionRef: tx.txRef,
autoEscalated: score >= 70,
}).catch(() => {});
// Fluvio velocity processor: publish AML event for real-time velocity checks (non-blocking)
fluvioPublishAmlEvent({
alert_id: newAlert.id,
alert_type: riskLevel,
risk_score: score,
transaction_ref: tx.txRef,
tenant_id: String((ctx.user as { tenantId?: string | number } | null)?.tenantId ?? "default"),
auto_escalated: score >= 70,
}).catch(() => {});
// Temporal: start AML workflow for critical/high alerts (non-blocking)
if (score >= 70) {
startAmlWorkflow({ investigationRef: `AML-${Date.now()}`, subjectName: input.originatorName, subjectType: "individual", triggerReason: "auto_escalation", riskScore: score, transactionRef: tx.txRef }).catch(e => console.warn("[AML Temporal]", e));
}
// Lakehouse: write AML alert event for analytics (non-blocking)
writeLakehouseEvent({ table: "aml_alert", data: { alertId: newAlert.id, riskScore: score,
riskLevel, transactionRef: tx.txRef, amount: input.amount,
currency: input.currency, originatorName: input.originatorName,
beneficiaryName: input.beneficiaryName,
}}).catch(() => {});
// Permify: write AML alert relationship for access control
void permifyWriteRelationship([{ entity: { type: "aml_alert", id: String(newAlert.id) }, relation: "owner", subject: { type: "user", id: String(ctx.user.id) } }]).catch(e => console.warn("[AML Permify]", e));
// Webhook fan-out: notify all subscribed tenants (non-blocking)
dispatchAmlWebhook({
tenantId,
event: "aml.alert",
riskLevel,
title: newAlert.title ?? `AML Alert ${newAlert.alertRef ?? `ALT-\${String(newAlert.id).padStart(6, "0")}`}`,
transactionId: tx.id,
amount: input.amount,
currency: input.currency,
originatorName: input.originatorName,
beneficiaryName: input.beneficiaryName,
flags,
timestamp: new Date().toISOString(),
}).catch(() => {});
}
return tx;
}),
flag: writeProcedure
.input(z.object({ id: z.number(), reason: z.string().min(10) }))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
const [tx] = await db.update(transactions)
.set({ status: "flagged", flaggedAt: new Date(), flaggedBy: ctx.user.id, updatedAt: new Date() })
.where(and(eq(transactions.id, input.id), eq(transactions.tenantId, tenantId))).returning();
if (!tx) throw new Error("Transaction not found");
await db.insert(amlAlerts).values({ tenantId, alertRef: amlAlertRef(), transactionId: tx.id, status: "open", riskLevel: "high",
title: `Manually Flagged: ${tx.originatorName} → ${tx.beneficiaryName}`,
description: input.reason, triggeredValue: tx.amount,
});
return tx;
}),
clear: writeProcedure
.input(z.object({ id: z.number(), notes: z.string().optional() }))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
const [tx] = await db.update(transactions)
.set({ status: "completed", amlRiskLevel: "low", updatedAt: new Date() })
.where(and(eq(transactions.id, input.id), eq(transactions.tenantId, tenantId), eq(transactions.status, "flagged"))).returning();
if (!tx) throw new Error("Only a tenant-owned flagged transaction can be cleared");
return tx;
}),
stats: protectedProcedure.query(async ({ ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const [totals] = await db.select({
total: count(),
totalAmount: sum(transactions.amount),
flagged: sql<number>`count(*) filter (where ${transactions.status} = 'flagged')`,
highRisk: sql<number>`count(*) filter (where ${transactions.amlRiskLevel} in ('high','critical'))`,
}).from(transactions).where(ctx.tenantId !== null ? eq(transactions.tenantId, ctx.tenantId) : undefined);
return {
total: Number(totals.total), totalAmount: Number(totals.totalAmount ?? 0),
flagged: Number(totals.flagged), highRisk: Number(totals.highRisk),
};
}),
// ─── AML Engine (Rust) direct screening ──────────────────────────────────────────
screenWithEngine: writeProcedure
.input(z.object({
type: z.string(),
amount: z.number().positive(),
currency: z.string().length(3).default("NGN"),
originatorName: z.string(),
originatorAccount: z.string().optional(),
originatorCountry: z.string().length(2).default("NG"),
beneficiaryName: z.string(),
beneficiaryAccount: z.string().optional(),
beneficiaryCountry: z.string().length(2).default("NG"),
narration: z.string().optional(),
}))
.mutation(async ({ input }) => {
const engineResult = await callAmlEngine("/v1/screen", {
transaction_type: input.type,
amount: input.amount,
currency: input.currency,
originator_name: input.originatorName,
originator_account: input.originatorAccount,
originator_country: input.originatorCountry,
beneficiary_name: input.beneficiaryName,
beneficiary_account: input.beneficiaryAccount,
beneficiary_country: input.beneficiaryCountry,
narration: input.narration,
});
// Fall back to local scoring if engine is offline
const localResult = scoreTransaction({
amount: input.amount, currency: input.currency,
originatorCountry: input.originatorCountry, beneficiaryCountry: input.beneficiaryCountry,
type: input.type, narration: input.narration,
});
return {
engineResult,
localScore: localResult.score,
localFlags: localResult.flags,
engineOnline: engineResult !== null,
riskLevel: localResult.score >= 70 ? "critical" : localResult.score >= 50 ? "high" : localResult.score >= 25 ? "medium" : "low",
};
}),
engineHealth: protectedProcedure.query(async () => {
try {
const res = await fetch(`${AML_ENGINE_URL}/health`, { signal: AbortSignal.timeout(3_000) });
const data = await res.json();
return { online: res.ok, ...data };
} catch {
return { online: false, status: "unreachable" };
}
}),
}),
alerts: router({
list: protectedProcedure
.input(z.object({
limit: z.number().min(1).max(250).default(50), offset: z.number().default(0),
status: z.string().optional(), riskLevel: z.string().optional(),
}))
.query(async ({ input, ctx }) => {
const cacheKey = `aml:alerts:tenant:${ctx.tenantId ?? "global"}:${input.status ?? "all"}:${input.riskLevel ?? "all"}:${input.offset}`;
return withCache(cacheKey, TTL.ALERTS_LIST, async () => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const conditions = [];
// Tenant isolation: non-admin users only see their own tenant's AML alerts
if (ctx.tenantId !== null) conditions.push(eq(amlAlerts.tenantId, ctx.tenantId));
if (input.status) conditions.push(eq(amlAlerts.status, input.status as any));
if (input.riskLevel) conditions.push(eq(amlAlerts.riskLevel, input.riskLevel as any));
const where = conditions.length > 0 ? and(...conditions) : undefined;
const [rows, [{ total }]] = await Promise.all([
db.select().from(amlAlerts).where(where).orderBy(desc(amlAlerts.createdAt)).limit(input.limit).offset(input.offset),
db.select({ total: count() }).from(amlAlerts).where(where),
]);
return { items: rows, total };
});
}),
review: writeProcedure
.input(z.object({
id: z.number(),
status: z.enum(["under_review", "escalated", "cleared", "filed", "false_positive"]),
notes: z.string().optional(),
investigationId: z.number().optional(),
}))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
// Permify: check that user can review this AML alert
const canReview = await permifyCheck("aml_alert", String(input.id), "update", String(ctx.user.id));
if (!canReview) throw new Error("Permission denied: cannot review AML alert");
const tenantCondition = ctx.tenantId !== null ? eq(amlAlerts.tenantId, ctx.tenantId) : undefined;
const [existing] = await db.select().from(amlAlerts)
.where(tenantCondition ? and(eq(amlAlerts.id, input.id), tenantCondition) : eq(amlAlerts.id, input.id));
if (!existing) throw new Error("AML alert not found");
assertLegalTransition(existing.status, input.status, {
open: ["under_review", "escalated", "cleared", "false_positive"],
under_review: ["escalated", "cleared", "filed", "false_positive"],
escalated: ["cleared", "filed"],
}, "AML alert");
const [alert] = await db.update(amlAlerts)
.set({ status: input.status, reviewedBy: ctx.user.id, reviewedAt: new Date(), reviewNotes: input.notes, investigationId: input.investigationId, updatedAt: new Date() })
.where(tenantCondition ? and(eq(amlAlerts.id, input.id), tenantCondition) : eq(amlAlerts.id, input.id)).returning();
// Dapr: publish status change event
void publishAmlAlert({ alertId: alert.id, alertType: alert.riskLevel ?? "medium", riskScore: 0, autoEscalated: false }).catch(() => {});
// Temporal: start AML escalation workflow if escalated
if (input.status === "escalated") {
startAmlWorkflow({ investigationRef: alert.alertRef ?? `ALT-${String(alert.id).padStart(6, "0")}`, subjectName: "Unknown", subjectType: "individual", triggerReason: "manual_escalation", alertRef: alert.alertRef ?? undefined, alertId: alert.id, riskScore: 0 }).catch(e => console.warn("[AML Temporal escalate]", e));
}
// Invalidate cached alert lists
void invalidateCache(`aml:alerts:tenant:${ctx.tenantId ?? "global"}`).catch(() => {});
return alert;
}),
stats: protectedProcedure.query(async ({ ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantCondition = ctx.tenantId !== null ? eq(amlAlerts.tenantId, ctx.tenantId) : undefined;
const [totals] = await db.select({
total: count(),
open: sql<number>`count(*) filter (where ${amlAlerts.status} = 'open')`,
escalated: sql<number>`count(*) filter (where ${amlAlerts.status} = 'escalated')`,
cleared: sql<number>`count(*) filter (where ${amlAlerts.status} = 'cleared')`,
critical: sql<number>`count(*) filter (where ${amlAlerts.riskLevel} = 'critical')`,
}).from(amlAlerts).where(tenantCondition);
return {
total: Number(totals.total), open: Number(totals.open),
escalated: Number(totals.escalated), cleared: Number(totals.cleared), critical: Number(totals.critical),
};
}),
}),
rules: router({
list: protectedProcedure.query(async () => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
return db.select().from(amlRules).orderBy(desc(amlRules.createdAt));
}),
create: adminProcedure
.input(z.object({
name: z.string().min(3), description: z.string().optional(),
ruleType: z.enum(["threshold", "velocity", "structuring", "round_trip", "layering",
"high_risk_country", "pep_transaction", "sanctions_match", "unusual_pattern"]),
threshold: z.number().optional(), currency: z.string().length(3).default("NGN"),
windowHours: z.number().default(24),
riskLevel: z.enum(["low", "medium", "high", "critical"]).default("medium"),
}))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const [rule] = await db.insert(amlRules).values({ ...input, createdBy: ctx.user.id }).returning();
return rule;
}),
toggle: adminProcedure
.input(z.object({ id: z.number(), enabled: z.boolean() }))
.mutation(async ({ input }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const [rule] = await db.update(amlRules).set({ enabled: input.enabled, updatedAt: new Date() }).where(eq(amlRules.id, input.id)).returning();
return rule;
}),
delete: adminProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
await db.delete(amlRules).where(eq(amlRules.id, input.id));
return { success: true };
}),
}),
swift: router({
list: protectedProcedure
.input(z.object({
limit: z.number().min(1).max(250).default(50), offset: z.number().default(0),
status: z.string().optional(), messageType: z.string().optional(), search: z.string().optional(),
}))
.query(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const conditions = [];
if (ctx.tenantId !== null) conditions.push(eq(swiftMessages.tenantId, ctx.tenantId));
if (input.status) conditions.push(eq(swiftMessages.status, input.status as any));
if (input.messageType) conditions.push(eq(swiftMessages.messageType, input.messageType as any));
if (input.search) {
conditions.push(or(
like(swiftMessages.senderBic, `%${input.search}%`),
like(swiftMessages.receiverBic, `%${input.search}%`),
like(swiftMessages.uetr, `%${input.search}%`),
)!);
}
const where = conditions.length > 0 ? and(...conditions) : undefined;
const [rows, [{ total }]] = await Promise.all([
db.select().from(swiftMessages).where(where).orderBy(desc(swiftMessages.createdAt)).limit(input.limit).offset(input.offset),
db.select({ total: count() }).from(swiftMessages).where(where),
]);
return { items: rows, total };
}),
create: writeProcedure
.input(z.object({
messageType: z.enum(["MT103", "MT202", "MT202COV", "MT199", "MT299", "MT900", "MT910", "MT940", "MT950"]),
senderBic: z.string().min(8).max(11), receiverBic: z.string().min(8).max(11),
amount: z.number().positive(), currency: z.string().length(3),
valueDate: z.string().optional(), orderingCustomer: z.string().optional(),
beneficiaryCustomer: z.string().optional(), remittanceInfo: z.string().optional(),
rawMessage: z.string().optional(),
}))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
const [msg] = await db.insert(swiftMessages).values({
tenantId,
uetr: uetrGen(), messageType: input.messageType, status: "received",
senderBic: input.senderBic, receiverBic: input.receiverBic,
amount: input.amount, currency: input.currency,
valueDate: input.valueDate ? new Date(input.valueDate) : new Date(),
orderingCustomer: input.orderingCustomer, beneficiaryCustomer: input.beneficiaryCustomer,
remittanceInfo: input.remittanceInfo, rawMessage: input.rawMessage,
parsedFields: { field20: Date.now().toString(36).toUpperCase() },
complianceStatus: "pending",
}).returning();
return msg;
}),
updateCompliance: writeProcedure
.input(z.object({
id: z.number(),
complianceStatus: z.enum(["pending", "cleared", "blocked", "escalated"]),
notes: z.string().optional(),
}))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
const [existing] = await db.select().from(swiftMessages)
.where(and(eq(swiftMessages.id, input.id), eq(swiftMessages.tenantId, tenantId)));
if (!existing) throw new Error("SWIFT message not found");
assertLegalTransition(existing.complianceStatus ?? "pending", input.complianceStatus, {
pending: ["cleared", "blocked", "escalated"],
escalated: ["cleared", "blocked"],
}, "SWIFT compliance");
const newStatus = input.complianceStatus === "cleared" ? "completed" : input.complianceStatus === "blocked" ? "rejected" : "pending_compliance";
const [msg] = await db.update(swiftMessages)
.set({ complianceStatus: input.complianceStatus, complianceNotes: input.notes, status: newStatus as any, updatedAt: new Date() })
.where(and(eq(swiftMessages.id, input.id), eq(swiftMessages.tenantId, tenantId))).returning();
return msg;
}),
}),
sepa: router({
list: protectedProcedure
.input(z.object({ limit: z.number().min(1).max(250).default(50), offset: z.number().default(0), status: z.string().optional() }))
.query(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const conditions = [];
if (ctx.tenantId !== null) conditions.push(eq(sepaPayments.tenantId, ctx.tenantId));
if (input.status) conditions.push(eq(sepaPayments.status, input.status as any));
const where = conditions.length ? and(...conditions) : undefined;
const [rows, [{ total }]] = await Promise.all([
db.select().from(sepaPayments).where(where).orderBy(desc(sepaPayments.createdAt)).limit(input.limit).offset(input.offset),
db.select({ total: count() }).from(sepaPayments).where(where),
]);
return { items: rows, total };
}),
create: writeProcedure
.input(z.object({
paymentType: z.enum(["credit_transfer", "direct_debit", "instant_credit"]),
amount: z.number().positive(), currency: z.string().length(3).default("EUR"),
debtorName: z.string().min(2), debtorIban: z.string().min(15).max(34),
debtorBic: z.string().optional(), creditorName: z.string().min(2),
creditorIban: z.string().min(15).max(34), creditorBic: z.string().optional(),
remittanceInfo: z.string().optional(), executionDate: z.string().optional(),
}))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
const endToEndId = `E2E-${Date.now().toString(36).toUpperCase()}-${crypto.randomUUID().replace(/-/g,'').slice(0,6).toUpperCase()}`;
const [payment] = await db.insert(sepaPayments).values({
tenantId,
endToEndId, ...input,
executionDate: input.executionDate ? new Date(input.executionDate) : new Date(),
}).returning();
return payment;
}),
settle: writeProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
const [payment] = await db.update(sepaPayments)
.set({ status: "settled", settlementDate: new Date() })
.where(and(eq(sepaPayments.id, input.id), eq(sepaPayments.tenantId, tenantId), eq(sepaPayments.status, "accepted"))).returning();
if (!payment) throw new Error("Only a tenant-owned accepted SEPA payment can be settled");
return payment;
}),
}),
travelRule: router({
list: protectedProcedure
.input(z.object({ limit: z.number().min(1).max(250).default(50), offset: z.number().default(0), status: z.string().optional() }))
.query(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const conditions = [];
if (ctx.tenantId !== null) conditions.push(eq(travelRuleRecords.tenantId, ctx.tenantId));
if (input.status) conditions.push(eq(travelRuleRecords.status, input.status as any));
const where = conditions.length ? and(...conditions) : undefined;
const [rows, [{ total }]] = await Promise.all([
db.select().from(travelRuleRecords).where(where).orderBy(desc(travelRuleRecords.createdAt)).limit(input.limit).offset(input.offset),
db.select({ total: count() }).from(travelRuleRecords).where(where),
]);
return { items: rows, total };
}),
create: writeProcedure
.input(z.object({
transactionId: z.number().optional(), thresholdAmount: z.number().default(1000),
currency: z.string().length(3).default("USD"),
originatorName: z.string().min(2), originatorAccount: z.string().optional(),
originatorAddress: z.string().optional(), originatorCountry: z.string().length(2).optional(),
originatorDob: z.string().optional(), originatorId: z.string().optional(),
beneficiaryName: z.string().min(2), beneficiaryAccount: z.string().optional(),
beneficiaryAddress: z.string().optional(), beneficiaryCountry: z.string().length(2).optional(),
vasp: z.string().optional(),
}))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
if (input.transactionId) {
const [transaction] = await db.select({ id: transactions.id }).from(transactions)
.where(and(eq(transactions.id, input.transactionId), eq(transactions.tenantId, tenantId)));
if (!transaction) throw new Error("Transaction not found");
}
const ref = `TR-${Date.now().toString(36).toUpperCase()}-${crypto.randomUUID().replace(/-/g,'').slice(0,5).toUpperCase()}`;
const [record] = await db.insert(travelRuleRecords).values({ tenantId, recordRef: ref, ...input, status: "pending" }).returning();
return record;
}),
send: writeProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
const [record] = await db.update(travelRuleRecords).set({ status: "sent", sentAt: new Date() })
.where(and(eq(travelRuleRecords.id, input.id), eq(travelRuleRecords.tenantId, tenantId), eq(travelRuleRecords.status, "pending"))).returning();
if (!record) throw new Error("Only a tenant-owned pending Travel Rule record can be sent");
// Publish Travel Rule sent event to Dapr pub/sub for compliance engine (non-blocking)
publishAmlAlert({alertId: 0,
alertType: "travel_rule_sent",
riskScore: 50,
subjectRef: record?.originatorName ?? undefined,
transactionRef: record?.recordRef ?? undefined,
timestamp: new Date().toISOString(),
}).catch(() => {});
return record;
}),
acknowledge: writeProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input, ctx }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const tenantId = requireTenantId(ctx);
const [record] = await db.update(travelRuleRecords).set({ status: "acknowledged", acknowledgedAt: new Date() })
.where(and(eq(travelRuleRecords.id, input.id), eq(travelRuleRecords.tenantId, tenantId), eq(travelRuleRecords.status, "sent"))).returning();
if (!record) throw new Error("Only a tenant-owned sent Travel Rule record can be acknowledged");
// Publish Travel Rule acknowledged event to Dapr pub/sub for compliance engine (non-blocking)
publishAmlAlert({alertId: 0,
alertType: "travel_rule_acknowledged",
riskScore: 0,
subjectRef: record?.originatorName ?? undefined,
transactionRef: record?.recordRef ?? undefined,
timestamp: new Date().toISOString(),
}).catch(() => {});
return record;
}),
}),
// ── Velocity Blocks ──────────────────────────────────────────────────────────
/**
* List velocity blocks recorded by the Fluvio sliding-window engine.
* Used by the AML dashboard to surface blocked transfers for compliance review.
*/
listVelocityBlocks: adminProcedure
.input(z.object({
accountId: z.string().optional(),
limit: z.number().int().min(1).max(200).default(50),
offset: z.number().int().min(0).default(0),
}))
.query(async ({ input }) => {
const db = await getDb();
if (!db) throw new Error("Database unavailable");
const conditions = input.accountId ? [eq(velocityBlocks.accountId, input.accountId)] : [];
const rows = await db
.select()
.from(velocityBlocks)
.where(conditions.length ? and(...conditions) : undefined)
.orderBy(desc(velocityBlocks.createdAt))
.limit(input.limit)
.offset(input.offset);
const [{ total }] = await db
.select({ total: count() })
.from(velocityBlocks)
.where(conditions.length ? and(...conditions) : undefined);
return { rows, total };
}),
});