@africode/core 5.0.10 → 5.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/AGENTS.md +585 -585
  2. package/AGENT_INSTRUCTIONS.md +595 -595
  3. package/COMPONENT_SCHEMA.json +1826 -1800
  4. package/LICENSE +623 -623
  5. package/README.md +476 -476
  6. package/bin/africode.js +73 -73
  7. package/bin/cli.ts +82 -82
  8. package/bin/create-africode.js +220 -220
  9. package/bin/scaffold.ts +218 -218
  10. package/components/accordion.js +183 -183
  11. package/components/alert.js +131 -131
  12. package/components/auth-form.js +154 -154
  13. package/components/auth.js +172 -172
  14. package/components/avatar.js +117 -117
  15. package/components/badge.js +104 -104
  16. package/components/base.d.ts +139 -139
  17. package/components/base.js +234 -234
  18. package/components/breadcrumb.js +76 -72
  19. package/components/button.js +164 -164
  20. package/components/card.js +144 -137
  21. package/components/carousel.js +32 -32
  22. package/components/cart-drawer.js +28 -28
  23. package/components/code-block.js +20 -20
  24. package/components/contact-form.js +25 -25
  25. package/components/cookie-consent.js +23 -23
  26. package/components/cta-banner.js +38 -38
  27. package/components/cultural-card.js +243 -243
  28. package/components/dashboard-activity-list.js +103 -103
  29. package/components/dashboard-card.js +85 -85
  30. package/components/dashboard-metric.js +81 -81
  31. package/components/dashboard-shell.js +85 -85
  32. package/components/dashboard-topbar.js +84 -84
  33. package/components/divider.js +83 -83
  34. package/components/dropdown.js +171 -171
  35. package/components/error-boundary.js +155 -155
  36. package/components/faq-accordion.js +23 -23
  37. package/components/feature-grid.js +85 -85
  38. package/components/file-uploader.js +22 -22
  39. package/components/filter-bar.js +19 -19
  40. package/components/footer.js +113 -113
  41. package/components/form.js +131 -131
  42. package/components/gallery.js +22 -22
  43. package/components/hero.js +140 -138
  44. package/components/icon.js +36 -36
  45. package/components/index.js +128 -128
  46. package/components/input.js +252 -256
  47. package/components/kanga-card.js +185 -185
  48. package/components/kyc-upload.js +173 -173
  49. package/components/language-switcher.js +108 -108
  50. package/components/loader.js +80 -80
  51. package/components/modal.js +262 -262
  52. package/components/motion.js +84 -84
  53. package/components/nav-drawer.js +216 -216
  54. package/components/navbar.js +243 -236
  55. package/components/newsletter-signup.js +24 -24
  56. package/components/pagination.js +31 -31
  57. package/components/pattern-showcase.js +225 -225
  58. package/components/pricing-card.js +100 -100
  59. package/components/product-card.js +41 -41
  60. package/components/progress.js +132 -134
  61. package/components/react.js +111 -111
  62. package/components/search-box.js +24 -24
  63. package/components/section.js +54 -54
  64. package/components/select.js +321 -322
  65. package/components/sidebar.js +180 -180
  66. package/components/simple-chart.js +22 -22
  67. package/components/skeleton.js +85 -85
  68. package/components/stepper.js +28 -28
  69. package/components/table.js +181 -181
  70. package/components/tabs.js +202 -202
  71. package/components/team-grid.js +23 -23
  72. package/components/testimonial.js +94 -94
  73. package/components/theme-toggle.js +82 -82
  74. package/components/toast.js +139 -139
  75. package/components/tooltip.js +167 -167
  76. package/components/transaction-ledger.js +138 -138
  77. package/components/ui-avatar.js +79 -79
  78. package/components/ui-badge.js +61 -61
  79. package/components/ui-button.js +149 -149
  80. package/components/ui-card.js +74 -75
  81. package/components/ui-chip.js +87 -87
  82. package/components/ui-input.js +110 -110
  83. package/components/ui-popover.js +84 -84
  84. package/components/ui-progress-ring.js +60 -60
  85. package/components/ui-select.js +85 -85
  86. package/components/ui-stat.js +75 -75
  87. package/components/ui-switch.js +85 -85
  88. package/components/ui-table.js +69 -69
  89. package/components/ui-tabs.js +99 -99
  90. package/components/ui-tag.js +64 -64
  91. package/components/ui-textarea.js +84 -84
  92. package/components/ui-tooltip.js +66 -66
  93. package/components/video-player.js +22 -22
  94. package/components/wallet-balance.js +114 -114
  95. package/core/a2ui-schema-manager.js +351 -351
  96. package/core/a2ui.js +696 -696
  97. package/core/actions.js +27 -27
  98. package/core/bun-runtime.js +398 -397
  99. package/core/cli/commands/add.js +23 -23
  100. package/core/cli/commands/audit.js +58 -58
  101. package/core/cli/commands/build.js +193 -193
  102. package/core/cli/commands/create-plugin.js +241 -241
  103. package/core/cli/commands/dev.js +252 -285
  104. package/core/cli/commands/lint.js +23 -23
  105. package/core/cli/commands/test.js +33 -34
  106. package/core/cli/migrator.js +71 -71
  107. package/core/cli/ui.js +56 -56
  108. package/core/compliance.js +823 -823
  109. package/core/config.js +265 -265
  110. package/core/db-advanced.js +478 -481
  111. package/core/db.js +282 -284
  112. package/core/enhanced-hmr.js +406 -406
  113. package/core/errors.js +222 -222
  114. package/core/file-router.js +52 -50
  115. package/core/hmr-client.js +203 -204
  116. package/core/hmr.js +205 -197
  117. package/core/html.d.ts +30 -30
  118. package/core/html.js +84 -84
  119. package/core/hydration.js +52 -52
  120. package/core/lipa-namba-journey.js +548 -605
  121. package/core/logging.js +14 -14
  122. package/core/middleware.js +145 -145
  123. package/core/motion.js +106 -106
  124. package/core/nida-cig-middleware.js +417 -460
  125. package/core/patterns.d.ts +124 -124
  126. package/core/patterns.js +947 -1001
  127. package/core/plugins/index.js +345 -345
  128. package/core/request-analytics.js +253 -253
  129. package/core/request-identity.js +93 -93
  130. package/core/router.js +386 -386
  131. package/core/sdk-browser.js +140 -140
  132. package/core/sdk-client.js +61 -61
  133. package/core/sdk.d.ts +133 -133
  134. package/core/sdk.js +148 -148
  135. package/core/seo.js +76 -76
  136. package/core/server/auth-endpoints.js +339 -339
  137. package/core/server/auth.js +180 -180
  138. package/core/server/csrf.js +200 -206
  139. package/core/server/db.js +39 -39
  140. package/core/server/middleware.js +324 -324
  141. package/core/server/rate-limit.js +238 -238
  142. package/core/server/render.js +67 -69
  143. package/core/server/router.js +102 -120
  144. package/core/session-store.js +68 -68
  145. package/core/shim.js +28 -28
  146. package/core/state.d.ts +86 -86
  147. package/core/state.js +276 -276
  148. package/core/store.d.ts +122 -122
  149. package/core/store.js +61 -61
  150. package/core/validation.d.ts +232 -232
  151. package/core/validation.js +602 -602
  152. package/core/websocket.js +656 -641
  153. package/dist/africode.js +233 -230
  154. package/dist/africode.js.map +83 -83
  155. package/dist/build-info.json +3 -3
  156. package/dist/components.js +195 -192
  157. package/dist/components.js.map +73 -73
  158. package/dist/styles/africanity.css +321 -321
  159. package/dist/styles/typography.css +140 -140
  160. package/docs/IDE-Guide.md +50 -50
  161. package/package.json +113 -113
  162. package/scripts/generate-component-schema.js +82 -79
  163. package/styles/africanity.css +321 -321
  164. package/styles/typography.css +140 -140
  165. package/templates/starter/.env.example +15 -15
  166. package/templates/starter/africode.config.js +40 -40
  167. package/templates/starter/package.json +13 -13
  168. package/templates/starter/src/index.js +18 -18
  169. package/templates/starter/src/pages/index.html +55 -55
  170. package/templates/starter/src/pages/index.js +17 -17
  171. package/templates/starter/src/styles/main.css +3 -3
  172. package/templates/starter-3d/.env.example +7 -7
  173. package/templates/starter-3d/africode.config.js +29 -29
  174. package/templates/starter-3d/components/af-model-viewer.js +125 -125
  175. package/templates/starter-3d/package.json +14 -14
  176. package/templates/starter-3d/src/pages/index.html +55 -55
  177. package/templates/starter-3d/src/pages/index.js +50 -50
  178. package/templates/starter-3d/src/styles/main.css +3 -3
  179. package/templates/starter-dashboard/.env.example +21 -21
  180. package/templates/starter-dashboard/africode.config.js +20 -20
  181. package/templates/starter-dashboard/package.json +14 -14
  182. package/templates/starter-dashboard/src/index.js +17 -17
  183. package/templates/starter-dashboard/src/pages/api/analytics.js +24 -24
  184. package/templates/starter-dashboard/src/pages/index.html +118 -118
  185. package/templates/starter-dashboard/src/pages/index.js +110 -110
  186. package/templates/starter-dashboard/src/styles/main.css +172 -172
  187. package/templates/starter-fintech/.env.example +28 -28
  188. package/templates/starter-fintech/africode.config.js +20 -20
  189. package/templates/starter-fintech/package.json +15 -15
  190. package/templates/starter-fintech/src/index.js +17 -17
  191. package/templates/starter-fintech/src/pages/api/auth.js +45 -45
  192. package/templates/starter-fintech/src/pages/api/dashboard.js +19 -0
  193. package/templates/starter-fintech/src/pages/api/transfer.js +65 -65
  194. package/templates/starter-fintech/src/pages/api/wallet.js +39 -39
  195. package/templates/starter-fintech/src/pages/api/webhooks/payment.js +32 -32
  196. package/templates/starter-fintech/src/pages/index.html +169 -169
  197. package/templates/starter-fintech/src/pages/index.js +161 -161
  198. package/templates/starter-fintech/src/styles/main.css +246 -246
  199. package/templates/starter-react/.env.example +15 -15
  200. package/templates/starter-react/africode.config.js +40 -40
  201. package/templates/starter-react/package.json +15 -15
  202. package/templates/starter-react/src/pages/index.html +55 -55
  203. package/templates/starter-react/src/pages/index.js +68 -68
  204. package/templates/starter-react/src/styles/main.css +3 -3
  205. package/templates/starter-tailwind/.env.example +15 -15
  206. package/templates/starter-tailwind/africode.config.js +40 -40
  207. package/templates/starter-tailwind/package.json +19 -19
  208. package/templates/starter-tailwind/src/pages/index.html +55 -55
  209. package/templates/starter-tailwind/src/pages/index.js +67 -67
  210. package/templates/starter-tailwind/src/styles/main.css +3 -3
  211. package/templates/starter-tailwind/src/styles/tailwind.css +1 -1
  212. package/templates/starter-tailwind/src/tailwind-loader.js +30 -30
  213. package/templates/starter-tailwind/tailwind.config.cjs +18 -18
  214. package/templates/starter-website/.env.example +18 -18
  215. package/templates/starter-website/africode.config.js +20 -20
  216. package/templates/starter-website/package.json +14 -14
  217. package/templates/starter-website/src/index.js +17 -17
  218. package/templates/starter-website/src/pages/index.html +124 -124
  219. package/templates/starter-website/src/pages/index.js +116 -116
  220. package/templates/starter-website/src/styles/main.css +195 -195
  221. package/bin/africode.js.1758507140 +0 -343
  222. package/core/heartbeat.js +0 -64
@@ -1,823 +1,823 @@
1
- /**
2
- * Fintech Compliance Engine
3
- * Tanzanian regulatory compliance for NIDA, TIPS, and AML/FIU
4
- *
5
- * Implements the "operating system" approach to compliance with
6
- * automated identity verification, transaction monitoring, and
7
- * regulatory reporting.
8
- *
9
- * @module core/compliance
10
- */
11
-
12
- import { z } from 'zod';
13
- import { frameworkLog } from './logging.js';
14
-
15
- /**
16
- * NIDA Identity Infrastructure Integration
17
- * National Identification Authority verification system
18
- */
19
- export class NIDAClient {
20
- constructor(config = {}) {
21
- this.baseUrl = config.baseUrl || 'https://api.nida.go.tz';
22
- this.apiKey = config.apiKey;
23
- this.certificate = config.certificate;
24
- this.timeout = config.timeout || 30000;
25
- }
26
-
27
- /**
28
- * Verify National ID Number (NIN)
29
- * @param {string} nin - 20-digit NIN
30
- * @param {Object} options - Verification options
31
- */
32
- async verifyNIN(nin, options = {}) {
33
- const schema = z.string().length(20).regex(/^\d{20}$/);
34
- schema.parse(nin);
35
-
36
- const response = await this._makeRequest('/verify/nin', {
37
- method: 'POST',
38
- body: JSON.stringify({
39
- nin,
40
- includeBiometrics: options.includeBiometrics || false,
41
- includeDemographics: options.includeDemographics || true
42
- })
43
- });
44
-
45
- return {
46
- verified: response.verified,
47
- demographics: response.demographics,
48
- biometrics: response.biometrics,
49
- confidence: response.confidence,
50
- timestamp: new Date().toISOString()
51
- };
52
- }
53
-
54
- /**
55
- * Perform biometric verification
56
- * @param {string} nin - NIN to verify against
57
- * @param {Object} biometrics - Biometric data
58
- */
59
- async verifyBiometrics(nin, biometrics) {
60
- const response = await this._makeRequest('/verify/biometrics', {
61
- method: 'POST',
62
- body: JSON.stringify({
63
- nin,
64
- fingerprint: biometrics.fingerprint,
65
- facialImage: biometrics.facialImage,
66
- livenessData: biometrics.livenessData
67
- })
68
- });
69
-
70
- return {
71
- match: response.match,
72
- confidence: response.confidence,
73
- level: response.level // ISO 30107-3 PAD level
74
- };
75
- }
76
-
77
- /**
78
- * Extract data from ID document
79
- * @param {File|Buffer} document - ID document image
80
- * @param {string} type - Document type (1-7 Tanzanian ID types)
81
- */
82
- async extractDocumentData(document, type) {
83
- const formData = new FormData();
84
- formData.append('document', document);
85
- formData.append('type', type);
86
-
87
- const response = await this._makeRequest('/extract/document', {
88
- method: 'POST',
89
- body: formData
90
- });
91
-
92
- return {
93
- extractedData: response.data,
94
- confidence: response.confidence,
95
- ocrText: response.ocrText
96
- };
97
- }
98
-
99
- /**
100
- * Make authenticated request to NIDA API
101
- */
102
- async _makeRequest(endpoint, options = {}) {
103
- const url = `${this.baseUrl}${endpoint}`;
104
-
105
- const headers = {
106
- 'Authorization': `Bearer ${this.apiKey}`,
107
- 'Content-Type': 'application/json',
108
- ...options.headers
109
- };
110
-
111
- // Add certificate-based authentication for production
112
- if (this.certificate) {
113
- headers['X-Client-Certificate'] = this.certificate;
114
- }
115
-
116
- const response = await fetch(url, {
117
- ...options,
118
- headers,
119
- signal: AbortSignal.timeout(this.timeout)
120
- });
121
-
122
- if (!response.ok) {
123
- throw new Error(`NIDA API error: ${response.status} ${response.statusText}`);
124
- }
125
-
126
- return response.json();
127
- }
128
- }
129
-
130
- /**
131
- * TIPS Payment System Integration
132
- * Tanzania Instant Payment System for real-time transactions
133
- */
134
- export class TIPSClient {
135
- constructor(config = {}) {
136
- this.baseUrl = config.baseUrl || 'https://api.tips.go.tz';
137
- this.apiKey = config.apiKey;
138
- this.clientId = config.clientId;
139
- this.privateKey = config.privateKey;
140
- this.timeout = config.timeout || 10000; // TIPS requires fast responses
141
- }
142
-
143
- /**
144
- * Process P2P payment
145
- * @param {Object} payment - Payment details
146
- */
147
- async processP2P(payment) {
148
- const schema = z.object({
149
- fromAccount: z.string(),
150
- toAccount: z.string(),
151
- amount: z.number().positive(),
152
- currency: z.string().default('TZS'),
153
- description: z.string().optional()
154
- });
155
-
156
- const validatedPayment = schema.parse(payment);
157
-
158
- const response = await this._makeRequest('/payments/p2p', {
159
- method: 'POST',
160
- body: JSON.stringify({
161
- ...validatedPayment,
162
- timestamp: new Date().toISOString(),
163
- idempotencyKey: this._generateIdempotencyKey()
164
- })
165
- });
166
-
167
- return {
168
- transactionId: response.transactionId,
169
- status: response.status,
170
- processedAt: response.processedAt,
171
- fee: response.fee
172
- };
173
- }
174
-
175
- /**
176
- * Process P2B payment (merchant payment)
177
- * @param {Object} payment - Payment details
178
- */
179
- async processP2B(payment) {
180
- const schema = z.object({
181
- customerAccount: z.string(),
182
- merchantAccount: z.string(),
183
- amount: z.number().positive(),
184
- reference: z.string(),
185
- description: z.string().optional()
186
- });
187
-
188
- const validatedPayment = schema.parse(payment);
189
-
190
- const response = await this._makeRequest('/payments/p2b', {
191
- method: 'POST',
192
- body: JSON.stringify(validatedPayment)
193
- });
194
-
195
- return {
196
- transactionId: response.transactionId,
197
- status: response.status,
198
- confirmationCode: response.confirmationCode
199
- };
200
- }
201
-
202
- /**
203
- * Request to Pay (RTP) - merchant requests payment from customer
204
- * @param {Object} request - RTP details
205
- */
206
- async requestToPay(request) {
207
- const schema = z.object({
208
- merchantAccount: z.string(),
209
- customerAccount: z.string(),
210
- amount: z.number().positive(),
211
- expiryMinutes: z.number().min(1).max(60).default(15),
212
- description: z.string()
213
- });
214
-
215
- const validatedRequest = schema.parse(request);
216
-
217
- const response = await this._makeRequest('/payments/rtp', {
218
- method: 'POST',
219
- body: JSON.stringify(validatedRequest)
220
- });
221
-
222
- return {
223
- requestId: response.requestId,
224
- status: response.status,
225
- expiryAt: response.expiryAt
226
- };
227
- }
228
-
229
- /**
230
- * Reverse transaction
231
- * @param {string} transactionId - Transaction to reverse
232
- * @param {string} reason - Reversal reason
233
- */
234
- async reverseTransaction(transactionId, reason) {
235
- const response = await this._makeRequest('/payments/reverse', {
236
- method: 'POST',
237
- body: JSON.stringify({
238
- transactionId,
239
- reason,
240
- timestamp: new Date().toISOString()
241
- })
242
- });
243
-
244
- return {
245
- reversalId: response.reversalId,
246
- status: response.status,
247
- reversedAt: response.reversedAt
248
- };
249
- }
250
-
251
- /**
252
- * Get transaction status
253
- * @param {string} transactionId - Transaction ID
254
- */
255
- async getTransactionStatus(transactionId) {
256
- const response = await this._makeRequest(`/payments/${transactionId}/status`);
257
- return response;
258
- }
259
-
260
- /**
261
- * Generate idempotency key for request deduplication
262
- */
263
- _generateIdempotencyKey() {
264
- return `tips_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
265
- }
266
-
267
- /**
268
- * Make authenticated request to TIPS API
269
- */
270
- async _makeRequest(endpoint, options = {}) {
271
- const url = `${this.baseUrl}${endpoint}`;
272
-
273
- // Create signature for request authentication
274
- const timestamp = new Date().toISOString();
275
- const signature = await this._createSignature(options.body || '', timestamp);
276
-
277
- const headers = {
278
- 'Authorization': `Bearer ${this.apiKey}`,
279
- 'X-Client-ID': this.clientId,
280
- 'X-Timestamp': timestamp,
281
- 'X-Signature': signature,
282
- 'Content-Type': 'application/json',
283
- ...options.headers
284
- };
285
-
286
- const response = await fetch(url, {
287
- ...options,
288
- headers,
289
- signal: AbortSignal.timeout(this.timeout)
290
- });
291
-
292
- if (!response.ok) {
293
- throw new Error(`TIPS API error: ${response.status} ${response.statusText}`);
294
- }
295
-
296
- return response.json();
297
- }
298
-
299
- /**
300
- * Create cryptographic signature for TIPS authentication
301
- */
302
- async _createSignature(body, timestamp) {
303
- const message = `${timestamp}${body}`;
304
- const encoder = new TextEncoder();
305
- const data = encoder.encode(message);
306
-
307
- // Use Web Crypto API for signing
308
- const key = await crypto.subtle.importKey(
309
- 'pkcs8',
310
- this._base64ToArrayBuffer(this.privateKey),
311
- {
312
- name: 'RSASSA-PKCS1-v1_5',
313
- hash: 'SHA-256'
314
- },
315
- false,
316
- ['sign']
317
- );
318
-
319
- const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, data);
320
- return this._arrayBufferToBase64(signature);
321
- }
322
-
323
- _base64ToArrayBuffer(base64) {
324
- const binaryString = atob(base64);
325
- const bytes = new Uint8Array(binaryString.length);
326
- for (let i = 0; i < binaryString.length; i++) {
327
- bytes[i] = binaryString.charCodeAt(i);
328
- }
329
- return bytes.buffer;
330
- }
331
-
332
- _arrayBufferToBase64(buffer) {
333
- const bytes = new Uint8Array(buffer);
334
- let binary = '';
335
- for (let i = 0; i < bytes.byteLength; i++) {
336
- binary += String.fromCharCode(bytes[i]);
337
- }
338
- return btoa(binary);
339
- }
340
- }
341
-
342
- /**
343
- * AML/FIU Compliance Engine
344
- * Automated Anti-Money Laundering and Financial Intelligence Unit integration
345
- */
346
- export class AMLComplianceEngine {
347
- constructor(config = {}) {
348
- this.fiuEndpoint = config.fiuEndpoint || 'https://api.fiu.go.tz';
349
- this.reportingWindow = config.reportingWindow || 24; // hours
350
- this.monitoringRules = config.monitoringRules || this._defaultRules();
351
- }
352
-
353
- /**
354
- * Evaluate transaction for suspicious activity
355
- * @param {Object} transaction - Transaction details
356
- * @param {Object} customer - Customer profile
357
- */
358
- async evaluateTransaction(transaction, customer) {
359
- const riskScore = await this._calculateRiskScore(transaction, customer);
360
- const flags = await this._checkMonitoringRules(transaction, customer);
361
-
362
- const isSuspicious = riskScore > 0.7 || flags.length > 0;
363
-
364
- if (isSuspicious) {
365
- await this._queueForReporting(transaction, customer, riskScore, flags);
366
- }
367
-
368
- return {
369
- riskScore,
370
- flags,
371
- suspicious: isSuspicious,
372
- evaluatedAt: new Date().toISOString()
373
- };
374
- }
375
-
376
- /**
377
- * Submit suspicious activity report to FIU
378
- * @param {Object} report - SAR details
379
- */
380
- async submitSAR(report) {
381
- const schema = z.object({
382
- transactionId: z.string(),
383
- customerId: z.string(),
384
- activityType: z.string(),
385
- description: z.string(),
386
- riskScore: z.number(),
387
- flags: z.array(z.string()),
388
- evidence: z.array(z.object({
389
- type: z.string(),
390
- data: z.any()
391
- }))
392
- });
393
-
394
- const validatedReport = schema.parse(report);
395
-
396
- const response = await fetch(`${this.fiuEndpoint}/sar`, {
397
- method: 'POST',
398
- headers: {
399
- 'Content-Type': 'application/json',
400
- 'Authorization': `Bearer ${process.env.FIU_API_KEY}`
401
- },
402
- body: JSON.stringify({
403
- ...validatedReport,
404
- submittedAt: new Date().toISOString(),
405
- reportingEntity: process.env.FINTECH_LICENSE_ID
406
- })
407
- });
408
-
409
- if (!response.ok) {
410
- throw new Error(`FIU submission failed: ${response.status}`);
411
- }
412
-
413
- return response.json();
414
- }
415
-
416
- /**
417
- * Calculate risk score for transaction
418
- */
419
- async _calculateRiskScore(transaction, customer) {
420
- let score = 0;
421
-
422
- // Amount-based scoring
423
- if (transaction.amount > 1000000) {
424
- score += 0.3; // > 1M TZS
425
- } else if (transaction.amount > 500000) {
426
- score += 0.2;
427
- }
428
-
429
- // Velocity checks
430
- const recentTransactions = await this._getRecentTransactions(customer.id, 24);
431
- if (recentTransactions.length > 10) {
432
- score += 0.2;
433
- }
434
-
435
- // Geographic anomalies
436
- if (this._isGeographicAnomaly(transaction, customer)) {
437
- score += 0.3;
438
- }
439
-
440
- // Customer risk profile
441
- if (customer.riskLevel === 'high') {
442
- score += 0.4;
443
- } else if (customer.riskLevel === 'medium') {
444
- score += 0.2;
445
- }
446
-
447
- return Math.min(score, 1.0);
448
- }
449
-
450
- /**
451
- * Check transaction against monitoring rules
452
- */
453
- async _checkMonitoringRules(transaction, customer) {
454
- const flags = [];
455
-
456
- for (const rule of this.monitoringRules) {
457
- if (await rule.check(transaction, customer)) {
458
- flags.push(rule.name);
459
- }
460
- }
461
-
462
- return flags;
463
- }
464
-
465
- /**
466
- * Enhanced risk scoring for African markets
467
- */
468
- async _calculateAfricanRiskScore(transaction, customer) {
469
- let score = await this._calculateRiskScore(transaction, customer);
470
-
471
- // Additional African-specific checks
472
-
473
- // Check for transactions involving multiple African countries
474
- if (transaction.crossBorder) {
475
- score += 0.15;
476
- }
477
-
478
- // Check for cryptocurrency-related activities
479
- if (transaction.paymentMethod?.includes('crypto')) {
480
- score += 0.25;
481
- }
482
-
483
- // Check for mobile money transactions (common in Africa)
484
- if (transaction.paymentMethod === 'mobile_money' && amount > 500000) { // 500k TZS
485
- score += 0.1;
486
- }
487
-
488
- // Check for politically exposed persons (PEPs)
489
- if (customer.isPEP) {
490
- score += 0.3;
491
- }
492
-
493
- // Check for high-risk sectors common in Africa
494
- if (customer.businessSector && ['casino', 'gambling', 'cash_intensive'].includes(customer.businessSector)) {
495
- score += 0.2;
496
- }
497
-
498
- return Math.min(score, 1.0);
499
- }
500
-
501
- /**
502
- * Multi-country sanctions screening
503
- */
504
- async screenSanctions(parties) {
505
- // Screen against OFAC, UN, EU, and African Union sanctions lists
506
- const results = [];
507
-
508
- for (const party of parties) {
509
- const sanctionsCheck = {
510
- name: party.name,
511
- id: party.id,
512
- matchedLists: [],
513
- riskLevel: 'low'
514
- };
515
-
516
- // In a real implementation, this would query sanctions databases
517
- // This is a simplified version
518
- if (party.name.toLowerCase().includes('sanctioned')) {
519
- sanctionsCheck.matchedLists.push('internal_watchlist');
520
- sanctionsCheck.riskLevel = 'high';
521
- }
522
-
523
- results.push(sanctionsCheck);
524
- }
525
-
526
- return results;
527
- }
528
-
529
- /**
530
- * Queue suspicious activity for FIU reporting
531
- */
532
- async _queueForReporting(transaction, customer, riskScore, flags) {
533
- const report = {
534
- transactionId: transaction.id,
535
- customerId: customer.id,
536
- activityType: 'suspicious_transaction',
537
- description: `High-risk transaction detected: ${flags.join(', ')}`,
538
- riskScore,
539
- flags,
540
- evidence: [
541
- { type: 'transaction', data: transaction },
542
- { type: 'customer', data: customer }
543
- ]
544
- };
545
-
546
- // Queue for reporting within 24-hour window
547
- await this._scheduleReporting(report, this.reportingWindow);
548
- }
549
-
550
- /**
551
- * Default AML monitoring rules
552
- */
553
- _defaultRules() {
554
- return [
555
- {
556
- name: 'large_amount',
557
- check: (tx) => tx.amount > 2000000 // > 2M TZS
558
- },
559
- {
560
- name: 'rapid_transactions',
561
- check: async (tx, customer) => {
562
- const recent = await this._getRecentTransactions(customer.id, 1);
563
- return recent.length > 5;
564
- }
565
- },
566
- {
567
- name: 'unusual_location',
568
- check: (tx, customer) => this._isGeographicAnomaly(tx, customer)
569
- }
570
- ];
571
- }
572
-
573
- /**
574
- * Check for geographic anomalies
575
- */
576
- _isGeographicAnomaly(transaction, customer) {
577
- // Simplified geographic check
578
- const customerCountry = customer.address?.country || 'TZ';
579
- const transactionCountry = transaction.location?.country || 'TZ';
580
-
581
- return customerCountry !== transactionCountry;
582
- }
583
-
584
- /**
585
- * Get recent transactions for customer
586
- */
587
- async _getRecentTransactions(_customerId, _hours) {
588
- // Implementation would query transaction database
589
- // Placeholder for demo
590
- void _customerId;
591
- void _hours;
592
- return [];
593
- }
594
-
595
- /**
596
- * Schedule reporting within compliance window
597
- */
598
- async _scheduleReporting(report, hours) {
599
- // Implementation would use job queue system
600
- frameworkLog('warn', `Scheduling FIU report in ${hours} hours for transaction ${report.transactionId}`);
601
- }
602
- }
603
-
604
- /**
605
- * Compliance Middleware
606
- * Framework-level compliance enforcement
607
- */
608
- export class ComplianceMiddleware {
609
- constructor(config = {}) {
610
- this.nida = config.nida ? new NIDAClient(config.nida) : null;
611
- this.tips = config.tips ? new TIPSClient(config.tips) : null;
612
- this.aml = new AMLComplianceEngine(config.aml);
613
- }
614
-
615
- /**
616
- * KYC middleware for identity verification
617
- */
618
- kycMiddleware() {
619
- return async (request, next) => {
620
- if (!this.nida) {
621
- return next(request);
622
- }
623
-
624
- const userId = request.session?.userId;
625
- if (!userId) {
626
- return next(request);
627
- }
628
-
629
- // Check if user needs KYC verification
630
- const user = await this._getUser(userId);
631
- if (!user.kycVerified) {
632
- // Perform NIDA verification
633
- try {
634
- const verification = await this.nida.verifyNIN(user.nin);
635
- if (verification.verified) {
636
- await this._updateUserKYC(userId, verification);
637
- }
638
- } catch (error) {
639
- frameworkLog('error', 'NIDA verification failed:', error);
640
- // Allow request to continue but log failure
641
- }
642
- }
643
-
644
- return next(request);
645
- };
646
- }
647
-
648
- /**
649
- * Transaction monitoring middleware
650
- */
651
- transactionMiddleware() {
652
- return async (transaction, next) => {
653
- const customer = await this._getCustomer(transaction.customerId);
654
-
655
- const evaluation = await this.aml.evaluateTransaction(transaction, customer);
656
-
657
- if (evaluation.suspicious) {
658
- frameworkLog('warn', `Suspicious transaction detected: ${transaction.id}`);
659
- // Could block transaction or flag for review
660
- }
661
-
662
- return next(transaction);
663
- };
664
- }
665
-
666
- /**
667
- * Get user by ID
668
- */
669
- async _getUser(userId) {
670
- // Implementation would query user database
671
- return { id: userId, kycVerified: false, nin: '12345678901234567890' };
672
- }
673
-
674
- /**
675
- * Update user KYC status
676
- */
677
- async _updateUserKYC(userId, verification) {
678
- // Implementation would update user database
679
- frameworkLog('warn', `Updated KYC for user ${userId}:`, verification);
680
- }
681
-
682
- /**
683
- * Get customer by ID
684
- */
685
- async _getCustomer(customerId) {
686
- // Implementation would query customer database
687
- return {
688
- id: customerId,
689
- riskLevel: 'low',
690
- address: { country: 'TZ' }
691
- };
692
- }
693
- }
694
-
695
- /**
696
- * African Payment Systems Compliance
697
- * Integration with regional payment systems and compliance requirements
698
- */
699
- export class AfricanPaymentCompliance {
700
- constructor(config = {}) {
701
- this.supportedCountries = config.countries || ['TZ', 'KE', 'UG', 'RW', 'ZA'];
702
- this.mobileMoneyProviders = config.providers || ['Mpesa', 'TigoPesa', 'AirtelMoney', 'MTNMobileMoney'];
703
- this.currencyThresholds = config.thresholds || {
704
- TZS: 1000000, // 1M TZS
705
- KES: 50000, // 50K KES
706
- UGX: 2000000, // 2M UGX
707
- ZAR: 2500 // 2.5K ZAR
708
- };
709
- }
710
-
711
- /**
712
- * Validate mobile money transaction
713
- * @param {Object} transaction - Transaction details
714
- * @param {Object} sender - Sender profile
715
- * @param {Object} receiver - Receiver profile
716
- */
717
- async validateMobileMoneyTransaction(transaction, sender, receiver) {
718
- const validation = {
719
- valid: true,
720
- warnings: [],
721
- errors: []
722
- };
723
-
724
- // Check if countries are supported
725
- if (!this.supportedCountries.includes(transaction.senderCountry)) {
726
- validation.errors.push('Sender country not supported');
727
- validation.valid = false;
728
- }
729
-
730
- if (!this.supportedCountries.includes(transaction.receiverCountry)) {
731
- validation.errors.push('Receiver country not supported');
732
- validation.valid = false;
733
- }
734
-
735
- // Check if provider is supported
736
- if (!this.mobileMoneyProviders.includes(transaction.provider)) {
737
- validation.warnings.push('Provider not in standard list');
738
- }
739
-
740
- // Check amount thresholds
741
- const threshold = this.currencyThresholds[transaction.currency];
742
- if (threshold && transaction.amount > threshold) {
743
- validation.warnings.push(`Amount exceeds recommended threshold for ${transaction.currency}`);
744
-
745
- // May require additional verification
746
- if (transaction.amount > threshold * 2) {
747
- validation.warnings.push('Amount significantly above threshold - enhanced due diligence recommended');
748
- }
749
- }
750
-
751
- // Check for frequent transactions (possible structuring)
752
- if (sender.dailyTransactionCount > 10) {
753
- validation.warnings.push('High frequency of transactions today');
754
- }
755
-
756
- return validation;
757
- }
758
-
759
- /**
760
- * Generate compliance report for mobile money transactions
761
- */
762
- async generateMobileMoneyReport(transactions, period) {
763
- const report = {
764
- period,
765
- totalTransactions: transactions.length,
766
- totalVolume: 0,
767
- byCountry: {},
768
- flaggedTransactions: []
769
- };
770
-
771
- for (const tx of transactions) {
772
- report.totalVolume += tx.amount;
773
-
774
- // Group by country
775
- if (!report.byCountry[tx.senderCountry]) {
776
- report.byCountry[tx.senderCountry] = {
777
- count: 0,
778
- volume: 0
779
- };
780
- }
781
-
782
- report.byCountry[tx.senderCountry].count++;
783
- report.byCountry[tx.senderCountry].volume += tx.amount;
784
-
785
- // Flag suspicious patterns
786
- if (tx.amount > this.currencyThresholds[tx.currency] * 2) {
787
- report.flaggedTransactions.push({
788
- id: tx.id,
789
- amount: tx.amount,
790
- reason: 'High value transaction'
791
- });
792
- }
793
- }
794
-
795
- return report;
796
- }
797
-
798
- /**
799
- * Cross-border transaction compliance
800
- */
801
- async validateCrossBorderTransaction(transaction) {
802
- const validation = {
803
- compliant: true,
804
- requirements: [],
805
- errors: []
806
- };
807
-
808
- // Check if transaction crosses borders
809
- if (transaction.senderCountry !== transaction.receiverCountry) {
810
- validation.requirements.push('cross_border_declaration');
811
- validation.requirements.push('purpose_of_transfer');
812
-
813
- // Higher scrutiny for cross-border
814
- if (transaction.amount > 5000000) { // 5M TZS
815
- validation.requirements.push('enhanced_verification');
816
- validation.requirements.push('source_of_funds');
817
- }
818
- }
819
-
820
- return validation;
821
- }
822
- }
823
-
1
+ /**
2
+ * Fintech Compliance Engine
3
+ * Tanzanian regulatory compliance for NIDA, TIPS, and AML/FIU
4
+ *
5
+ * Implements the "operating system" approach to compliance with
6
+ * automated identity verification, transaction monitoring, and
7
+ * regulatory reporting.
8
+ *
9
+ * @module core/compliance
10
+ */
11
+
12
+ import { z } from 'zod';
13
+ import { frameworkLog } from './logging.js';
14
+
15
+ /**
16
+ * NIDA Identity Infrastructure Integration
17
+ * National Identification Authority verification system
18
+ */
19
+ export class NIDAClient {
20
+ constructor(config = {}) {
21
+ this.baseUrl = config.baseUrl || 'https://api.nida.go.tz';
22
+ this.apiKey = config.apiKey;
23
+ this.certificate = config.certificate;
24
+ this.timeout = config.timeout || 30000;
25
+ }
26
+
27
+ /**
28
+ * Verify National ID Number (NIN)
29
+ * @param {string} nin - 20-digit NIN
30
+ * @param {Object} options - Verification options
31
+ */
32
+ async verifyNIN(nin, options = {}) {
33
+ const schema = z.string().length(20).regex(/^\d{20}$/);
34
+ schema.parse(nin);
35
+
36
+ const response = await this._makeRequest('/verify/nin', {
37
+ method: 'POST',
38
+ body: JSON.stringify({
39
+ nin,
40
+ includeBiometrics: options.includeBiometrics || false,
41
+ includeDemographics: options.includeDemographics || true
42
+ })
43
+ });
44
+
45
+ return {
46
+ verified: response.verified,
47
+ demographics: response.demographics,
48
+ biometrics: response.biometrics,
49
+ confidence: response.confidence,
50
+ timestamp: new Date().toISOString()
51
+ };
52
+ }
53
+
54
+ /**
55
+ * Perform biometric verification
56
+ * @param {string} nin - NIN to verify against
57
+ * @param {Object} biometrics - Biometric data
58
+ */
59
+ async verifyBiometrics(nin, biometrics) {
60
+ const response = await this._makeRequest('/verify/biometrics', {
61
+ method: 'POST',
62
+ body: JSON.stringify({
63
+ nin,
64
+ fingerprint: biometrics.fingerprint,
65
+ facialImage: biometrics.facialImage,
66
+ livenessData: biometrics.livenessData
67
+ })
68
+ });
69
+
70
+ return {
71
+ match: response.match,
72
+ confidence: response.confidence,
73
+ level: response.level // ISO 30107-3 PAD level
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Extract data from ID document
79
+ * @param {File|Buffer} document - ID document image
80
+ * @param {string} type - Document type (1-7 Tanzanian ID types)
81
+ */
82
+ async extractDocumentData(document, type) {
83
+ const formData = new FormData();
84
+ formData.append('document', document);
85
+ formData.append('type', type);
86
+
87
+ const response = await this._makeRequest('/extract/document', {
88
+ method: 'POST',
89
+ body: formData
90
+ });
91
+
92
+ return {
93
+ extractedData: response.data,
94
+ confidence: response.confidence,
95
+ ocrText: response.ocrText
96
+ };
97
+ }
98
+
99
+ /**
100
+ * Make authenticated request to NIDA API
101
+ */
102
+ async _makeRequest(endpoint, options = {}) {
103
+ const url = `${this.baseUrl}${endpoint}`;
104
+
105
+ const headers = {
106
+ 'Authorization': `Bearer ${this.apiKey}`,
107
+ 'Content-Type': 'application/json',
108
+ ...options.headers
109
+ };
110
+
111
+ // Add certificate-based authentication for production
112
+ if (this.certificate) {
113
+ headers['X-Client-Certificate'] = this.certificate;
114
+ }
115
+
116
+ const response = await fetch(url, {
117
+ ...options,
118
+ headers,
119
+ signal: AbortSignal.timeout(this.timeout)
120
+ });
121
+
122
+ if (!response.ok) {
123
+ throw new Error(`NIDA API error: ${response.status} ${response.statusText}`);
124
+ }
125
+
126
+ return response.json();
127
+ }
128
+ }
129
+
130
+ /**
131
+ * TIPS Payment System Integration
132
+ * Tanzania Instant Payment System for real-time transactions
133
+ */
134
+ export class TIPSClient {
135
+ constructor(config = {}) {
136
+ this.baseUrl = config.baseUrl || 'https://api.tips.go.tz';
137
+ this.apiKey = config.apiKey;
138
+ this.clientId = config.clientId;
139
+ this.privateKey = config.privateKey;
140
+ this.timeout = config.timeout || 10000; // TIPS requires fast responses
141
+ }
142
+
143
+ /**
144
+ * Process P2P payment
145
+ * @param {Object} payment - Payment details
146
+ */
147
+ async processP2P(payment) {
148
+ const schema = z.object({
149
+ fromAccount: z.string(),
150
+ toAccount: z.string(),
151
+ amount: z.number().positive(),
152
+ currency: z.string().default('TZS'),
153
+ description: z.string().optional()
154
+ });
155
+
156
+ const validatedPayment = schema.parse(payment);
157
+
158
+ const response = await this._makeRequest('/payments/p2p', {
159
+ method: 'POST',
160
+ body: JSON.stringify({
161
+ ...validatedPayment,
162
+ timestamp: new Date().toISOString(),
163
+ idempotencyKey: this._generateIdempotencyKey()
164
+ })
165
+ });
166
+
167
+ return {
168
+ transactionId: response.transactionId,
169
+ status: response.status,
170
+ processedAt: response.processedAt,
171
+ fee: response.fee
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Process P2B payment (merchant payment)
177
+ * @param {Object} payment - Payment details
178
+ */
179
+ async processP2B(payment) {
180
+ const schema = z.object({
181
+ customerAccount: z.string(),
182
+ merchantAccount: z.string(),
183
+ amount: z.number().positive(),
184
+ reference: z.string(),
185
+ description: z.string().optional()
186
+ });
187
+
188
+ const validatedPayment = schema.parse(payment);
189
+
190
+ const response = await this._makeRequest('/payments/p2b', {
191
+ method: 'POST',
192
+ body: JSON.stringify(validatedPayment)
193
+ });
194
+
195
+ return {
196
+ transactionId: response.transactionId,
197
+ status: response.status,
198
+ confirmationCode: response.confirmationCode
199
+ };
200
+ }
201
+
202
+ /**
203
+ * Request to Pay (RTP) - merchant requests payment from customer
204
+ * @param {Object} request - RTP details
205
+ */
206
+ async requestToPay(request) {
207
+ const schema = z.object({
208
+ merchantAccount: z.string(),
209
+ customerAccount: z.string(),
210
+ amount: z.number().positive(),
211
+ expiryMinutes: z.number().min(1).max(60).default(15),
212
+ description: z.string()
213
+ });
214
+
215
+ const validatedRequest = schema.parse(request);
216
+
217
+ const response = await this._makeRequest('/payments/rtp', {
218
+ method: 'POST',
219
+ body: JSON.stringify(validatedRequest)
220
+ });
221
+
222
+ return {
223
+ requestId: response.requestId,
224
+ status: response.status,
225
+ expiryAt: response.expiryAt
226
+ };
227
+ }
228
+
229
+ /**
230
+ * Reverse transaction
231
+ * @param {string} transactionId - Transaction to reverse
232
+ * @param {string} reason - Reversal reason
233
+ */
234
+ async reverseTransaction(transactionId, reason) {
235
+ const response = await this._makeRequest('/payments/reverse', {
236
+ method: 'POST',
237
+ body: JSON.stringify({
238
+ transactionId,
239
+ reason,
240
+ timestamp: new Date().toISOString()
241
+ })
242
+ });
243
+
244
+ return {
245
+ reversalId: response.reversalId,
246
+ status: response.status,
247
+ reversedAt: response.reversedAt
248
+ };
249
+ }
250
+
251
+ /**
252
+ * Get transaction status
253
+ * @param {string} transactionId - Transaction ID
254
+ */
255
+ async getTransactionStatus(transactionId) {
256
+ const response = await this._makeRequest(`/payments/${transactionId}/status`);
257
+ return response;
258
+ }
259
+
260
+ /**
261
+ * Generate idempotency key for request deduplication
262
+ */
263
+ _generateIdempotencyKey() {
264
+ return `tips_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
265
+ }
266
+
267
+ /**
268
+ * Make authenticated request to TIPS API
269
+ */
270
+ async _makeRequest(endpoint, options = {}) {
271
+ const url = `${this.baseUrl}${endpoint}`;
272
+
273
+ // Create signature for request authentication
274
+ const timestamp = new Date().toISOString();
275
+ const signature = await this._createSignature(options.body || '', timestamp);
276
+
277
+ const headers = {
278
+ 'Authorization': `Bearer ${this.apiKey}`,
279
+ 'X-Client-ID': this.clientId,
280
+ 'X-Timestamp': timestamp,
281
+ 'X-Signature': signature,
282
+ 'Content-Type': 'application/json',
283
+ ...options.headers
284
+ };
285
+
286
+ const response = await fetch(url, {
287
+ ...options,
288
+ headers,
289
+ signal: AbortSignal.timeout(this.timeout)
290
+ });
291
+
292
+ if (!response.ok) {
293
+ throw new Error(`TIPS API error: ${response.status} ${response.statusText}`);
294
+ }
295
+
296
+ return response.json();
297
+ }
298
+
299
+ /**
300
+ * Create cryptographic signature for TIPS authentication
301
+ */
302
+ async _createSignature(body, timestamp) {
303
+ const message = `${timestamp}${body}`;
304
+ const encoder = new TextEncoder();
305
+ const data = encoder.encode(message);
306
+
307
+ // Use Web Crypto API for signing
308
+ const key = await crypto.subtle.importKey(
309
+ 'pkcs8',
310
+ this._base64ToArrayBuffer(this.privateKey),
311
+ {
312
+ name: 'RSASSA-PKCS1-v1_5',
313
+ hash: 'SHA-256'
314
+ },
315
+ false,
316
+ ['sign']
317
+ );
318
+
319
+ const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, data);
320
+ return this._arrayBufferToBase64(signature);
321
+ }
322
+
323
+ _base64ToArrayBuffer(base64) {
324
+ const binaryString = atob(base64);
325
+ const bytes = new Uint8Array(binaryString.length);
326
+ for (let i = 0; i < binaryString.length; i++) {
327
+ bytes[i] = binaryString.charCodeAt(i);
328
+ }
329
+ return bytes.buffer;
330
+ }
331
+
332
+ _arrayBufferToBase64(buffer) {
333
+ const bytes = new Uint8Array(buffer);
334
+ let binary = '';
335
+ for (let i = 0; i < bytes.byteLength; i++) {
336
+ binary += String.fromCharCode(bytes[i]);
337
+ }
338
+ return btoa(binary);
339
+ }
340
+ }
341
+
342
+ /**
343
+ * AML/FIU Compliance Engine
344
+ * Automated Anti-Money Laundering and Financial Intelligence Unit integration
345
+ */
346
+ export class AMLComplianceEngine {
347
+ constructor(config = {}) {
348
+ this.fiuEndpoint = config.fiuEndpoint || 'https://api.fiu.go.tz';
349
+ this.reportingWindow = config.reportingWindow || 24; // hours
350
+ this.monitoringRules = config.monitoringRules || this._defaultRules();
351
+ }
352
+
353
+ /**
354
+ * Evaluate transaction for suspicious activity
355
+ * @param {Object} transaction - Transaction details
356
+ * @param {Object} customer - Customer profile
357
+ */
358
+ async evaluateTransaction(transaction, customer) {
359
+ const riskScore = await this._calculateRiskScore(transaction, customer);
360
+ const flags = await this._checkMonitoringRules(transaction, customer);
361
+
362
+ const isSuspicious = riskScore > 0.7 || flags.length > 0;
363
+
364
+ if (isSuspicious) {
365
+ await this._queueForReporting(transaction, customer, riskScore, flags);
366
+ }
367
+
368
+ return {
369
+ riskScore,
370
+ flags,
371
+ suspicious: isSuspicious,
372
+ evaluatedAt: new Date().toISOString()
373
+ };
374
+ }
375
+
376
+ /**
377
+ * Submit suspicious activity report to FIU
378
+ * @param {Object} report - SAR details
379
+ */
380
+ async submitSAR(report) {
381
+ const schema = z.object({
382
+ transactionId: z.string(),
383
+ customerId: z.string(),
384
+ activityType: z.string(),
385
+ description: z.string(),
386
+ riskScore: z.number(),
387
+ flags: z.array(z.string()),
388
+ evidence: z.array(z.object({
389
+ type: z.string(),
390
+ data: z.any()
391
+ }))
392
+ });
393
+
394
+ const validatedReport = schema.parse(report);
395
+
396
+ const response = await fetch(`${this.fiuEndpoint}/sar`, {
397
+ method: 'POST',
398
+ headers: {
399
+ 'Content-Type': 'application/json',
400
+ 'Authorization': `Bearer ${process.env.FIU_API_KEY}`
401
+ },
402
+ body: JSON.stringify({
403
+ ...validatedReport,
404
+ submittedAt: new Date().toISOString(),
405
+ reportingEntity: process.env.FINTECH_LICENSE_ID
406
+ })
407
+ });
408
+
409
+ if (!response.ok) {
410
+ throw new Error(`FIU submission failed: ${response.status}`);
411
+ }
412
+
413
+ return response.json();
414
+ }
415
+
416
+ /**
417
+ * Calculate risk score for transaction
418
+ */
419
+ async _calculateRiskScore(transaction, customer) {
420
+ let score = 0;
421
+
422
+ // Amount-based scoring
423
+ if (transaction.amount > 1000000) {
424
+ score += 0.3; // > 1M TZS
425
+ } else if (transaction.amount > 500000) {
426
+ score += 0.2;
427
+ }
428
+
429
+ // Velocity checks
430
+ const recentTransactions = await this._getRecentTransactions(customer.id, 24);
431
+ if (recentTransactions.length > 10) {
432
+ score += 0.2;
433
+ }
434
+
435
+ // Geographic anomalies
436
+ if (this._isGeographicAnomaly(transaction, customer)) {
437
+ score += 0.3;
438
+ }
439
+
440
+ // Customer risk profile
441
+ if (customer.riskLevel === 'high') {
442
+ score += 0.4;
443
+ } else if (customer.riskLevel === 'medium') {
444
+ score += 0.2;
445
+ }
446
+
447
+ return Math.min(score, 1.0);
448
+ }
449
+
450
+ /**
451
+ * Check transaction against monitoring rules
452
+ */
453
+ async _checkMonitoringRules(transaction, customer) {
454
+ const flags = [];
455
+
456
+ for (const rule of this.monitoringRules) {
457
+ if (await rule.check(transaction, customer)) {
458
+ flags.push(rule.name);
459
+ }
460
+ }
461
+
462
+ return flags;
463
+ }
464
+
465
+ /**
466
+ * Enhanced risk scoring for African markets
467
+ */
468
+ async _calculateAfricanRiskScore(transaction, customer) {
469
+ let score = await this._calculateRiskScore(transaction, customer);
470
+
471
+ // Additional African-specific checks
472
+
473
+ // Check for transactions involving multiple African countries
474
+ if (transaction.crossBorder) {
475
+ score += 0.15;
476
+ }
477
+
478
+ // Check for cryptocurrency-related activities
479
+ if (transaction.paymentMethod?.includes('crypto')) {
480
+ score += 0.25;
481
+ }
482
+
483
+ // Check for mobile money transactions (common in Africa)
484
+ if (transaction.paymentMethod === 'mobile_money' && transaction.amount > 500000) { // 500k TZS
485
+ score += 0.1;
486
+ }
487
+
488
+ // Check for politically exposed persons (PEPs)
489
+ if (customer.isPEP) {
490
+ score += 0.3;
491
+ }
492
+
493
+ // Check for high-risk sectors common in Africa
494
+ if (customer.businessSector && ['casino', 'gambling', 'cash_intensive'].includes(customer.businessSector)) {
495
+ score += 0.2;
496
+ }
497
+
498
+ return Math.min(score, 1.0);
499
+ }
500
+
501
+ /**
502
+ * Multi-country sanctions screening
503
+ */
504
+ async screenSanctions(parties) {
505
+ // Screen against OFAC, UN, EU, and African Union sanctions lists
506
+ const results = [];
507
+
508
+ for (const party of parties) {
509
+ const sanctionsCheck = {
510
+ name: party.name,
511
+ id: party.id,
512
+ matchedLists: [],
513
+ riskLevel: 'low'
514
+ };
515
+
516
+ // In a real implementation, this would query sanctions databases
517
+ // This is a simplified version
518
+ if (party.name.toLowerCase().includes('sanctioned')) {
519
+ sanctionsCheck.matchedLists.push('internal_watchlist');
520
+ sanctionsCheck.riskLevel = 'high';
521
+ }
522
+
523
+ results.push(sanctionsCheck);
524
+ }
525
+
526
+ return results;
527
+ }
528
+
529
+ /**
530
+ * Queue suspicious activity for FIU reporting
531
+ */
532
+ async _queueForReporting(transaction, customer, riskScore, flags) {
533
+ const report = {
534
+ transactionId: transaction.id,
535
+ customerId: customer.id,
536
+ activityType: 'suspicious_transaction',
537
+ description: `High-risk transaction detected: ${flags.join(', ')}`,
538
+ riskScore,
539
+ flags,
540
+ evidence: [
541
+ { type: 'transaction', data: transaction },
542
+ { type: 'customer', data: customer }
543
+ ]
544
+ };
545
+
546
+ // Queue for reporting within 24-hour window
547
+ await this._scheduleReporting(report, this.reportingWindow);
548
+ }
549
+
550
+ /**
551
+ * Default AML monitoring rules
552
+ */
553
+ _defaultRules() {
554
+ return [
555
+ {
556
+ name: 'large_amount',
557
+ check: (tx) => tx.amount > 2000000 // > 2M TZS
558
+ },
559
+ {
560
+ name: 'rapid_transactions',
561
+ check: async (tx, customer) => {
562
+ const recent = await this._getRecentTransactions(customer.id, 1);
563
+ return recent.length > 5;
564
+ }
565
+ },
566
+ {
567
+ name: 'unusual_location',
568
+ check: (tx, customer) => this._isGeographicAnomaly(tx, customer)
569
+ }
570
+ ];
571
+ }
572
+
573
+ /**
574
+ * Check for geographic anomalies
575
+ */
576
+ _isGeographicAnomaly(transaction, customer) {
577
+ // Simplified geographic check
578
+ const customerCountry = customer.address?.country || 'TZ';
579
+ const transactionCountry = transaction.location?.country || 'TZ';
580
+
581
+ return customerCountry !== transactionCountry;
582
+ }
583
+
584
+ /**
585
+ * Get recent transactions for customer
586
+ */
587
+ async _getRecentTransactions(_customerId, _hours) {
588
+ // Implementation would query transaction database
589
+ // Placeholder for demo
590
+ void _customerId;
591
+ void _hours;
592
+ return [];
593
+ }
594
+
595
+ /**
596
+ * Schedule reporting within compliance window
597
+ */
598
+ async _scheduleReporting(report, hours) {
599
+ // Implementation would use job queue system
600
+ frameworkLog('warn', `Scheduling FIU report in ${hours} hours for transaction ${report.transactionId}`);
601
+ }
602
+ }
603
+
604
+ /**
605
+ * Compliance Middleware
606
+ * Framework-level compliance enforcement
607
+ */
608
+ export class ComplianceMiddleware {
609
+ constructor(config = {}) {
610
+ this.nida = config.nida ? new NIDAClient(config.nida) : null;
611
+ this.tips = config.tips ? new TIPSClient(config.tips) : null;
612
+ this.aml = new AMLComplianceEngine(config.aml);
613
+ }
614
+
615
+ /**
616
+ * KYC middleware for identity verification
617
+ */
618
+ kycMiddleware() {
619
+ return async (request, next) => {
620
+ if (!this.nida) {
621
+ return next(request);
622
+ }
623
+
624
+ const userId = request.session?.userId;
625
+ if (!userId) {
626
+ return next(request);
627
+ }
628
+
629
+ // Check if user needs KYC verification
630
+ const user = await this._getUser(userId);
631
+ if (!user.kycVerified) {
632
+ // Perform NIDA verification
633
+ try {
634
+ const verification = await this.nida.verifyNIN(user.nin);
635
+ if (verification.verified) {
636
+ await this._updateUserKYC(userId, verification);
637
+ }
638
+ } catch (error) {
639
+ frameworkLog('error', 'NIDA verification failed:', error);
640
+ // Allow request to continue but log failure
641
+ }
642
+ }
643
+
644
+ return next(request);
645
+ };
646
+ }
647
+
648
+ /**
649
+ * Transaction monitoring middleware
650
+ */
651
+ transactionMiddleware() {
652
+ return async (transaction, next) => {
653
+ const customer = await this._getCustomer(transaction.customerId);
654
+
655
+ const evaluation = await this.aml.evaluateTransaction(transaction, customer);
656
+
657
+ if (evaluation.suspicious) {
658
+ frameworkLog('warn', `Suspicious transaction detected: ${transaction.id}`);
659
+ // Could block transaction or flag for review
660
+ }
661
+
662
+ return next(transaction);
663
+ };
664
+ }
665
+
666
+ /**
667
+ * Get user by ID
668
+ */
669
+ async _getUser(userId) {
670
+ // Implementation would query user database
671
+ return { id: userId, kycVerified: false, nin: '12345678901234567890' };
672
+ }
673
+
674
+ /**
675
+ * Update user KYC status
676
+ */
677
+ async _updateUserKYC(userId, verification) {
678
+ // Implementation would update user database
679
+ frameworkLog('warn', `Updated KYC for user ${userId}:`, verification);
680
+ }
681
+
682
+ /**
683
+ * Get customer by ID
684
+ */
685
+ async _getCustomer(customerId) {
686
+ // Implementation would query customer database
687
+ return {
688
+ id: customerId,
689
+ riskLevel: 'low',
690
+ address: { country: 'TZ' }
691
+ };
692
+ }
693
+ }
694
+
695
+ /**
696
+ * African Payment Systems Compliance
697
+ * Integration with regional payment systems and compliance requirements
698
+ */
699
+ export class AfricanPaymentCompliance {
700
+ constructor(config = {}) {
701
+ this.supportedCountries = config.countries || ['TZ', 'KE', 'UG', 'RW', 'ZA'];
702
+ this.mobileMoneyProviders = config.providers || ['Mpesa', 'TigoPesa', 'AirtelMoney', 'MTNMobileMoney'];
703
+ this.currencyThresholds = config.thresholds || {
704
+ TZS: 1000000, // 1M TZS
705
+ KES: 50000, // 50K KES
706
+ UGX: 2000000, // 2M UGX
707
+ ZAR: 2500 // 2.5K ZAR
708
+ };
709
+ }
710
+
711
+ /**
712
+ * Validate mobile money transaction
713
+ * @param {Object} transaction - Transaction details
714
+ * @param {Object} sender - Sender profile
715
+ * @param {Object} receiver - Receiver profile
716
+ */
717
+ async validateMobileMoneyTransaction(transaction, sender, _receiver) {
718
+ const validation = {
719
+ valid: true,
720
+ warnings: [],
721
+ errors: []
722
+ };
723
+
724
+ // Check if countries are supported
725
+ if (!this.supportedCountries.includes(transaction.senderCountry)) {
726
+ validation.errors.push('Sender country not supported');
727
+ validation.valid = false;
728
+ }
729
+
730
+ if (!this.supportedCountries.includes(transaction.receiverCountry)) {
731
+ validation.errors.push('Receiver country not supported');
732
+ validation.valid = false;
733
+ }
734
+
735
+ // Check if provider is supported
736
+ if (!this.mobileMoneyProviders.includes(transaction.provider)) {
737
+ validation.warnings.push('Provider not in standard list');
738
+ }
739
+
740
+ // Check amount thresholds
741
+ const threshold = this.currencyThresholds[transaction.currency];
742
+ if (threshold && transaction.amount > threshold) {
743
+ validation.warnings.push(`Amount exceeds recommended threshold for ${transaction.currency}`);
744
+
745
+ // May require additional verification
746
+ if (transaction.amount > threshold * 2) {
747
+ validation.warnings.push('Amount significantly above threshold - enhanced due diligence recommended');
748
+ }
749
+ }
750
+
751
+ // Check for frequent transactions (possible structuring)
752
+ if (sender.dailyTransactionCount > 10) {
753
+ validation.warnings.push('High frequency of transactions today');
754
+ }
755
+
756
+ return validation;
757
+ }
758
+
759
+ /**
760
+ * Generate compliance report for mobile money transactions
761
+ */
762
+ async generateMobileMoneyReport(transactions, period) {
763
+ const report = {
764
+ period,
765
+ totalTransactions: transactions.length,
766
+ totalVolume: 0,
767
+ byCountry: {},
768
+ flaggedTransactions: []
769
+ };
770
+
771
+ for (const tx of transactions) {
772
+ report.totalVolume += tx.amount;
773
+
774
+ // Group by country
775
+ if (!report.byCountry[tx.senderCountry]) {
776
+ report.byCountry[tx.senderCountry] = {
777
+ count: 0,
778
+ volume: 0
779
+ };
780
+ }
781
+
782
+ report.byCountry[tx.senderCountry].count++;
783
+ report.byCountry[tx.senderCountry].volume += tx.amount;
784
+
785
+ // Flag suspicious patterns
786
+ if (tx.amount > this.currencyThresholds[tx.currency] * 2) {
787
+ report.flaggedTransactions.push({
788
+ id: tx.id,
789
+ amount: tx.amount,
790
+ reason: 'High value transaction'
791
+ });
792
+ }
793
+ }
794
+
795
+ return report;
796
+ }
797
+
798
+ /**
799
+ * Cross-border transaction compliance
800
+ */
801
+ async validateCrossBorderTransaction(transaction) {
802
+ const validation = {
803
+ compliant: true,
804
+ requirements: [],
805
+ errors: []
806
+ };
807
+
808
+ // Check if transaction crosses borders
809
+ if (transaction.senderCountry !== transaction.receiverCountry) {
810
+ validation.requirements.push('cross_border_declaration');
811
+ validation.requirements.push('purpose_of_transfer');
812
+
813
+ // Higher scrutiny for cross-border
814
+ if (transaction.amount > 5000000) { // 5M TZS
815
+ validation.requirements.push('enhanced_verification');
816
+ validation.requirements.push('source_of_funds');
817
+ }
818
+ }
819
+
820
+ return validation;
821
+ }
822
+ }
823
+