@leonelmaken/kinyan 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,84 @@
1
+ // Traducteur CamPay -> Kinyan. CamPay ne parle pas GSMA : ce module le traduit.
2
+ // Points CamPay non documentés publiquement (à confirmer sur un compte démo) : format exact de la signature
3
+ // des notifications, refus ou non d'une external_reference déjà utilisée, forme de l'historique.
4
+ import crypto from 'node:crypto';
5
+ import { toDecimal } from '../money.mjs';
6
+ import { transition, applyProviderStatus, markUnknown, normalizeStatus, amountFrom } from '../payment.mjs';
7
+
8
+ export function campayProvider({ baseUrl = 'https://demo.campay.net', username, password, webhookKey, fetchImpl = fetch, timeoutMs = 20000 }) {
9
+ let token = null, tokenExp = 0;
10
+
11
+ async function auth(force = false) {
12
+ if (!force && token && Date.now() < tokenExp - 30_000) return token;
13
+ const r = await fetchImpl(`${baseUrl}/api/token/`, { method: 'POST', headers: { 'content-type': 'application/json' },
14
+ body: JSON.stringify({ username, password }), signal: AbortSignal.timeout(timeoutMs) });
15
+ if (r.status !== 200) throw new Error(`CamPay : authentification refusée (${r.status})`);
16
+ const j = await r.json(); token = j.token; tokenExp = Date.now() + Number(j.expires_in || 3600) * 1000; return token;
17
+ }
18
+ async function call(method, path, body) {
19
+ for (const retry of [false, true]) {
20
+ const r = await fetchImpl(baseUrl + path, { method, signal: AbortSignal.timeout(timeoutMs),
21
+ headers: { 'content-type': 'application/json', authorization: `Token ${await auth(retry)}` }, body: body ? JSON.stringify(body) : undefined });
22
+ if (r.status === 401 && !retry) continue; // jeton expiré : rien n'a été créé, relancer est sûr
23
+ let json = null; try { json = await r.json(); } catch { }
24
+ return { status: r.status, json };
25
+ }
26
+ }
27
+ const toRemote = t => ({ status: normalizeStatus(t.status), reference: t.reference, amount: amountFrom(t.amount, t.currency) });
28
+
29
+ return {
30
+ name: 'campay',
31
+
32
+ async initiate(p) {
33
+ p.provider.name = 'campay';
34
+ if (p.requested.currency !== 'XAF') throw new Error('CamPay encaisse en XAF');
35
+ const from = p.debitParty.find(x => x.key === 'msisdn')?.value;
36
+ let r;
37
+ try { r = await call('POST', '/api/collect/', { amount: toDecimal(p.requested), currency: 'XAF', from,
38
+ description: p.metadata.description || `Paiement ${p.id}`, external_reference: p.id }); }
39
+ catch { markUnknown(p, 'coupure réseau pendant la collecte'); return { outcome: 'unknown' }; }
40
+ if (r.status === 200) { p.provider.transactionReference = r.json.reference; transition(p, 'PENDING', 'collecte acceptée'); return { outcome: 'pending' }; }
41
+ if (r.status >= 500) { markUnknown(p, `erreur ${r.status} CamPay`); return { outcome: 'unknown' }; }
42
+ transition(p, 'FAILED', `${r.json?.error_code || r.status} ${r.json?.message || ''}`.trim());
43
+ return { outcome: 'failed', error: r.json };
44
+ },
45
+
46
+ // Sans référence CamPay (réponse perdue) : chercher notre external_reference dans l'historique.
47
+ // CamPay ne garantissant pas le refus des doublons, on ne relance JAMAIS la collecte automatiquement.
48
+ async recover(p) {
49
+ const r = await call('POST', '/api/history/', {});
50
+ const hit = r.status === 200 ? (r.json?.data || []).find(t => t.external_reference === p.id) : null;
51
+ if (!hit) return { outcome: 'not_found', safeToRetry: false };
52
+ p.provider.transactionReference = hit.reference;
53
+ return { outcome: 'recovered', effect: applyProviderStatus(p, toRemote(hit)) };
54
+ },
55
+
56
+ async refresh(p) {
57
+ if (!p.provider.transactionReference) return this.recover(p);
58
+ const r = await call('GET', `/api/transaction/${encodeURIComponent(p.provider.transactionReference)}/`);
59
+ return r.status === 200 ? { effect: applyProviderStatus(p, toRemote(r.json)) } : { effect: null };
60
+ },
61
+
62
+ // Lecture seule d'un paiement par sa référence CamPay. null = inconnu sur CE compte.
63
+ async lookup(reference) {
64
+ const r = await call('GET', `/api/transaction/${encodeURIComponent(reference)}/`);
65
+ // Constaté en bac à sable (déc. 2026) : référence au mauvais format -> 403 « Invalid transaction reference »,
66
+ // référence au bon format mais inconnue -> 404 « Not found ».
67
+ if (r.status === 404 || (r.status === 400 && !r.json?.status)) return null;
68
+ if (r.status === 403 && /invalid transaction reference/i.test(r.json?.message || '')) return null;
69
+ if (r.status !== 200) throw new Error(`CamPay : lecture impossible (${r.status})`);
70
+ return { ...toRemote(r.json), rawStatus: r.json.status, createdAt: r.json.created_at ?? null, completedAt: r.json.updated_at ?? null };
71
+ },
72
+
73
+ // Notification : vérifier la signature (refus si clé absente), puis appeler refresh() — jamais le corps reçu.
74
+ verifyNotification(query) {
75
+ if (!webhookKey) return false; // pas de clé = on refuse tout (fail closed)
76
+ const parts = String(query.signature || '').split('.');
77
+ if (parts.length !== 3) return false;
78
+ try { if (JSON.parse(Buffer.from(parts[0], 'base64url')).alg !== 'HS256') return false; } catch { return false; }
79
+ const expected = crypto.createHmac('sha256', webhookKey).update(`${parts[0]}.${parts[1]}`).digest();
80
+ const got = Buffer.from(parts[2], 'base64url');
81
+ return got.length === expected.length && crypto.timingSafeEqual(got, expected);
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,85 @@
1
+ // Traducteur pour tout fournisseur conforme au standard GSMA Mobile Money API (v1.2).
2
+ // Un seul traducteur = tous les fournisseurs qui parlent GSMA.
3
+ // - X-CorrelationID = id du paiement Kinyan : un 2e envoi est rejeté « DuplicateRequest », jamais débité deux fois
4
+ // - réponse perdue : GET /responses/{clientCorrelationId} retrouve la ressource créée
5
+ // - statut : GET /requeststates/{serverCorrelationId} puis GET /transactions/{reference}
6
+ import { toDecimal } from '../money.mjs';
7
+ import { transition, applyProviderStatus, markUnknown, normalizeStatus, amountFrom } from '../payment.mjs';
8
+
9
+ export function gsmaProvider({ baseUrl, headers = {}, callbackUrl = null, paths = {}, fetchImpl = fetch, timeoutMs = 20000 }) {
10
+ const P = { responses: '/responses', requestStates: '/requeststates', transactions: '/transactions', ...paths };
11
+
12
+ async function call(method, path, { body, correlationId } = {}) {
13
+ const h = { 'content-type': 'application/json', accept: 'application/json', ...headers };
14
+ if (correlationId) h['X-CorrelationID'] = correlationId;
15
+ if (callbackUrl && method === 'POST') h['X-Callback-URL'] = callbackUrl;
16
+ const url = path.startsWith('http') ? path : baseUrl + path;
17
+ const r = await fetchImpl(url, { method, headers: h, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(timeoutMs) });
18
+ let json = null; try { json = await r.json(); } catch { }
19
+ return { status: r.status, json };
20
+ }
21
+
22
+ const toRemote = tx => ({ status: normalizeStatus(tx.transactionStatus), reference: tx.transactionReference,
23
+ amount: amountFrom(tx.amount, tx.currency) });
24
+
25
+ async function readTransaction(p, ref) {
26
+ const r = await call('GET', `${P.transactions}/${encodeURIComponent(ref)}`);
27
+ if (r.status === 200) return applyProviderStatus(p, toRemote(r.json));
28
+ return null;
29
+ }
30
+
31
+ return {
32
+ name: 'gsma',
33
+
34
+ // Lance le paiement. Ne relance JAMAIS un appel dont le résultat est incertain.
35
+ async initiate(p) {
36
+ p.provider.name = 'gsma';
37
+ const body = { amount: toDecimal(p.requested), currency: p.requested.currency,
38
+ debitParty: p.debitParty, creditParty: p.creditParty, descriptionText: p.metadata.description,
39
+ requestingOrganisationTransactionReference: p.id };
40
+ let r;
41
+ try { r = await call('POST', `${P.transactions}/type/${p.type}`, { body, correlationId: p.id }); }
42
+ catch { markUnknown(p, 'coupure réseau pendant l\'envoi'); return { outcome: 'unknown' }; }
43
+
44
+ if (r.status === 200 || r.status === 201 || r.status === 202) {
45
+ const rs = r.json || {};
46
+ p.provider.serverCorrelationId = rs.serverCorrelationId || null;
47
+ if (rs.objectReference) p.provider.transactionReference = rs.objectReference;
48
+ if (rs.transactionReference) return { outcome: 'accepted', effect: applyProviderStatus(p, toRemote(rs)) };
49
+ if (rs.status === 'failed') { transition(p, 'FAILED', rs.errorReference?.errorCode || 'refusé'); return { outcome: 'failed' }; }
50
+ transition(p, 'PENDING', 'accepté par le fournisseur');
51
+ return { outcome: 'pending' };
52
+ }
53
+ if (r.status >= 500) { markUnknown(p, `erreur ${r.status} du fournisseur`); return { outcome: 'unknown' }; }
54
+ if (r.json?.errorCode === 'DuplicateRequest' || /duplicate/i.test(r.json?.errorCode || '')) return this.recover(p);
55
+ transition(p, 'FAILED', `${r.json?.errorCategory || 'erreur'} ${r.json?.errorCode || r.status}`);
56
+ return { outcome: 'failed', error: r.json };
57
+ },
58
+
59
+ // Réponse perdue : retrouver ce que le fournisseur a créé avec notre clientCorrelationId.
60
+ async recover(p) {
61
+ const r = await call('GET', `${P.responses}/${encodeURIComponent(p.id)}`);
62
+ if (r.status === 404) return { outcome: 'not_found', safeToRetry: true }; // rien n'est arrivé chez le fournisseur
63
+ if (r.status === 200 && r.json?.link) {
64
+ const t = await call('GET', r.json.link);
65
+ if (t.status === 200) return { outcome: 'recovered', effect: applyProviderStatus(p, toRemote(t.json)) };
66
+ }
67
+ return { outcome: 'unknown' };
68
+ },
69
+
70
+ // Relire le statut réel. À appeler sur notification, par le job de rapprochement, et avant toute expiration.
71
+ async refresh(p) {
72
+ if (p.provider.transactionReference) return { effect: await readTransaction(p, p.provider.transactionReference) };
73
+ if (p.provider.serverCorrelationId) {
74
+ const r = await call('GET', `${P.requestStates}/${encodeURIComponent(p.provider.serverCorrelationId)}`);
75
+ if (r.status === 200) {
76
+ if (r.json.objectReference) p.provider.transactionReference = r.json.objectReference;
77
+ if (r.json.status === 'completed' && r.json.objectReference) return { effect: await readTransaction(p, r.json.objectReference) };
78
+ if (r.json.status === 'failed') { transition(p, 'FAILED', r.json.errorReference?.errorCode || 'refusé'); return { effect: null }; }
79
+ return { effect: null };
80
+ }
81
+ }
82
+ return this.recover(p);
83
+ },
84
+ };
85
+ }
@@ -0,0 +1,78 @@
1
+ // Traducteur Notch Pay -> Kinyan.
2
+ // Faits vérifiés dans la doc officielle (developer.notchpay.co, déc. 2026) :
3
+ // - base https://api.notchpay.co, en-tête Authorization: <clé publique> (test_… ou live_…)
4
+ // - POST /payments {amount, currency, phone|email, reference, description, callback} -> transaction + authorization_url
5
+ // - GET /payments/{reference} -> transaction {reference, amount, currency, status, created_at, completed_at}
6
+ // - statuts : pending, processing, complete, failed, canceled, expired
7
+ // - webhook : en-tête X-Notch-Signature = HMAC-SHA256 hexadécimal du CORPS BRUT avec le secret du webhook
8
+ // Non documenté (à confirmer en bac à sable) : refus ou non d'une `reference` déjà utilisée.
9
+ import crypto from 'node:crypto';
10
+ import { toDecimal } from '../money.mjs';
11
+ import { transition, applyProviderStatus, markUnknown, normalizeStatus, amountFrom } from '../payment.mjs';
12
+
13
+ export function notchpayProvider({ baseUrl = 'https://api.notchpay.co', publicKey, webhookSecret, callbackUrl, fetchImpl = fetch, timeoutMs = 20000 }) {
14
+ if (!publicKey) throw new Error('Notch Pay : clé publique manquante (mets-la dans ton .env)');
15
+
16
+ async function call(method, path, body) {
17
+ const r = await fetchImpl(baseUrl + path, { method, signal: AbortSignal.timeout(timeoutMs),
18
+ headers: { 'content-type': 'application/json', accept: 'application/json', authorization: publicKey },
19
+ body: body ? JSON.stringify(body) : undefined });
20
+ let json = null; try { json = await r.json(); } catch { }
21
+ return { status: r.status, json };
22
+ }
23
+ const toRemote = t => ({ status: normalizeStatus(t.status), rawStatus: t.status, reference: t.reference,
24
+ amount: amountFrom(t.amount, t.currency), createdAt: t.created_at ?? null, completedAt: t.completed_at ?? null });
25
+
26
+ return {
27
+ name: 'notchpay',
28
+
29
+ async initiate(p) {
30
+ p.provider.name = 'notchpay';
31
+ const phone = p.debitParty.find(x => x.key === 'msisdn')?.value;
32
+ let r;
33
+ try { r = await call('POST', '/payments', { amount: Number(toDecimal(p.requested)), currency: p.requested.currency,
34
+ phone, reference: p.id, description: p.metadata.description || `Paiement ${p.id}`, callback: callbackUrl }); }
35
+ catch { markUnknown(p, 'coupure réseau pendant la création'); return { outcome: 'unknown' }; }
36
+ if (r.status === 200 || r.status === 201) {
37
+ p.provider.transactionReference = r.json?.transaction?.reference ?? null;
38
+ transition(p, 'PENDING', 'paiement créé chez Notch Pay');
39
+ return { outcome: 'pending', redirectUrl: r.json?.authorization_url ?? null };
40
+ }
41
+ if (r.status >= 500) { markUnknown(p, `erreur ${r.status} Notch Pay`); return { outcome: 'unknown' }; }
42
+ transition(p, 'FAILED', `${r.status} ${r.json?.message || ''}`.trim());
43
+ return { outcome: 'failed', error: r.json };
44
+ },
45
+
46
+ // Constaté en mode test (déc. 2026) : GET /payments/{ref} ne trouve QUE la référence Notch Pay (trx.…),
47
+ // pas la nôtre. Réponse perdue = pas de référence Notch Pay -> on ne sait pas, et on ne relance pas tout seul.
48
+ async recover(p) {
49
+ if (!p.provider.transactionReference) return { outcome: 'not_found', safeToRetry: false, effect: null };
50
+ return this.refresh(p);
51
+ },
52
+
53
+ async refresh(p) {
54
+ if (!p.provider.transactionReference) return this.recover(p);
55
+ const t = await this.lookup(p.provider.transactionReference);
56
+ if (!t) return { outcome: 'not_found', safeToRetry: false, effect: null };
57
+ p.provider.transactionReference = t.reference;
58
+ return { outcome: 'found', effect: applyProviderStatus(p, t) };
59
+ },
60
+
61
+ // Lecture seule d'un paiement par sa référence. null = inconnu sur CE compte.
62
+ async lookup(reference) {
63
+ const r = await call('GET', `/payments/${encodeURIComponent(reference)}`);
64
+ if (r.status === 404) return null;
65
+ if (r.status < 200 || r.status >= 300) throw new Error(`Notch Pay : lecture impossible (${r.status})`);
66
+ const t = r.json?.transaction || r.json?.data;
67
+ return t ? toRemote(t) : null;
68
+ },
69
+
70
+ // rawBody = corps BRUT (Buffer ou chaîne), pas le JSON reparsé. Pas de secret = on refuse tout.
71
+ verifyNotification(rawBody, signature) {
72
+ if (!webhookSecret || !signature) return false;
73
+ const expected = crypto.createHmac('sha256', webhookSecret).update(rawBody).digest();
74
+ let got; try { got = Buffer.from(String(signature).trim(), 'hex'); } catch { return false; }
75
+ return got.length === expected.length && crypto.timingSafeEqual(got, expected);
76
+ },
77
+ };
78
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ export * from './money.mjs';
2
+ export * from './payment.mjs';
3
+ export { recordSettlement, reconcile, totals } from './ledger.mjs';
4
+ export { createMandate, authorize } from './mandate.mjs';
5
+ export { gsmaProvider } from './adapters/gsma.mjs';
6
+ export { campayProvider } from './adapters/campay.mjs';
7
+ export { notchpayProvider } from './adapters/notchpay.mjs';
8
+ export { createVerifier, memoryStore, fileStore, demoProvider, VERDICTS } from './verify.mjs';
package/src/ledger.mjs ADDED
@@ -0,0 +1,63 @@
1
+ // Registre à trois montants et rapprochement.
2
+ // demandé : ce que l'appli a demandé au client
3
+ // confirmé : ce que le fournisseur dit avoir encaissé
4
+ // réglé : ce que l'entreprise reçoit vraiment (net de frais, parfois dans une autre devise :
5
+ // USD, EUR ou stablecoin USDC/USDT réglé « sous » le mobile money)
6
+ import { money, sub, add, convert, driftBps, format, equals } from './money.mjs';
7
+
8
+ // settlement : { gross, fee, net, fxRate?, batchId, settledAt } (gross/fee/net créés avec money())
9
+ export function recordSettlement(p, s) {
10
+ if (!s.batchId) throw new Error('batchId obligatoire (référence du relevé ou du lot)');
11
+ p.settlements.push({ ...s, recordedAt: new Date().toISOString() });
12
+ }
13
+
14
+ // Rapproche une liste de paiements. Retourne les écarts, chacun avec un code, une gravité et une explication.
15
+ export function reconcile(payments, { now = new Date(), maxSettlementDays = 3, fxToleranceBps = 150 } = {}) {
16
+ const issues = [];
17
+ const seenBatches = new Map();
18
+ const push = (p, code, severity, message, amount = null) => issues.push({ paymentId: p.id, code, severity, message, amount: amount ? format(amount) : null });
19
+
20
+ for (const p of payments) {
21
+ for (const s of p.settlements) {
22
+ const key = `${s.batchId}:${p.id}`;
23
+ if (seenBatches.has(key)) push(p, 'REGLEMENT_EN_DOUBLE', 'haute', `Le lot ${s.batchId} apparaît deux fois pour ce paiement`, s.net);
24
+ seenBatches.set(key, true);
25
+ try {
26
+ if (!equals(add(s.net, s.fee), s.gross)) push(p, 'NET_INCOHERENT', 'haute', `brut ${format(s.gross)} ≠ net ${format(s.net)} + frais ${format(s.fee)}`);
27
+ } catch { push(p, 'DEVISES_MELANGEES', 'haute', 'brut, net et frais doivent être dans la même devise'); }
28
+ if (!['PAID', 'NEEDS_REVIEW', 'REVERSED'].includes(p.status))
29
+ push(p, 'REGLE_MAIS_PAS_PAYE', 'haute', `Argent reçu (${format(s.net)}) pour un paiement en état ${p.status} : succès tardif ou paiement fantôme`, s.net);
30
+
31
+ if (s.gross.currency === p.requested.currency) {
32
+ if (!equals(s.gross, p.confirmed || p.requested)) push(p, 'BRUT_DIFFERENT', 'moyenne', `brut réglé ${format(s.gross)} ≠ confirmé ${format(p.confirmed || p.requested)}`);
33
+ } else if (s.fxRate) {
34
+ const expected = convert(p.confirmed || p.requested, s.gross.currency, s.fxRate);
35
+ const bps = driftBps(expected, s.gross);
36
+ if (bps > fxToleranceBps) push(p, 'ECART_DE_CHANGE', 'moyenne', `attendu ${format(expected)} au taux ${s.fxRate}, réglé ${format(s.gross)} (écart ${(bps / 100).toFixed(2)} %)`, s.gross);
37
+ } else push(p, 'TAUX_MANQUANT', 'moyenne', `réglé en ${s.gross.currency} sans taux de change enregistré`);
38
+ }
39
+ if (p.status === 'PAID' && p.settlements.length === 0) {
40
+ const paidAt = new Date([...p.history].reverse().find(h => h.to === 'PAID')?.at || now);
41
+ const days = (now - paidAt) / 86400000;
42
+ if (days > maxSettlementDays) push(p, 'REGLEMENT_MANQUANT', 'haute', `payé depuis ${Math.floor(days)} jour(s), aucun règlement reçu`, p.confirmed || p.requested);
43
+ }
44
+ }
45
+ return issues;
46
+ }
47
+
48
+ // Totaux par devise : demandé, confirmé, réglé net, frais.
49
+ export function totals(payments) {
50
+ const t = {};
51
+ const bucket = c => (t[c] ||= { demande: money(0n, c, { minor: true }), confirme: money(0n, c, { minor: true }), regle_net: money(0n, c, { minor: true }), frais: money(0n, c, { minor: true }) });
52
+ for (const p of payments) {
53
+ bucket(p.requested.currency).demande = add(bucket(p.requested.currency).demande, p.requested);
54
+ if (p.confirmed) bucket(p.confirmed.currency).confirme = add(bucket(p.confirmed.currency).confirme, p.confirmed);
55
+ for (const s of p.settlements) {
56
+ const b = bucket(s.net.currency);
57
+ b.regle_net = add(b.regle_net, s.net); b.frais = add(b.frais, s.fee);
58
+ }
59
+ }
60
+ return Object.fromEntries(Object.entries(t).map(([c, v]) => [c, Object.fromEntries(Object.entries(v).map(([k, m]) => [k, format(m)]))]));
61
+ }
62
+
63
+ export { sub };
@@ -0,0 +1,42 @@
1
+ // Mandat de paiement pour agents IA. Un agent n'hérite jamais des droits de l'humain : il reçoit
2
+ // un mandat limité (montant, plafond du jour, bénéficiaires, durée), et au-delà d'un seuil, un humain valide.
3
+ import crypto from 'node:crypto';
4
+ import { money, add } from './money.mjs';
5
+
6
+ export function createMandate({ agentId, currency, maxPerPayment, maxPerDay, humanApprovalAbove,
7
+ allowedCounterparties = [], allowedTypes = ['merchantpay', 'billpay'], expiresAt, purpose }) {
8
+ for (const [k, v] of Object.entries({ agentId, currency, maxPerPayment, maxPerDay, expiresAt, purpose }))
9
+ if (v == null) throw new Error(`Mandat incomplet : ${k} manquant`);
10
+ const m = v => money(String(v), currency);
11
+ return Object.freeze({
12
+ id: crypto.randomUUID(), agentId, currency, purpose,
13
+ maxPerPayment: m(maxPerPayment), maxPerDay: m(maxPerDay),
14
+ humanApprovalAbove: humanApprovalAbove == null ? null : m(humanApprovalAbove),
15
+ allowedCounterparties: Object.freeze([...allowedCounterparties]), allowedTypes: Object.freeze([...allowedTypes]),
16
+ expiresAt: new Date(expiresAt).toISOString(), createdAt: new Date().toISOString(),
17
+ });
18
+ }
19
+
20
+ // request : { amount: money, counterparty, type, idempotencyKey }
21
+ // spentToday : money déjà engagé aujourd'hui par cet agent sous ce mandat
22
+ // Retourne { decision: 'ALLOW' | 'NEEDS_HUMAN' | 'DENY', reasons: [...], audit }
23
+ export function authorize(mandate, request, { spentToday, now = new Date() } = {}) {
24
+ const deny = [], human = [];
25
+ if (now > new Date(mandate.expiresAt)) deny.push('mandat expiré');
26
+ if (!request.idempotencyKey) deny.push('clé d\'idempotence absente : un agent qui réessaie paierait deux fois');
27
+ if (request.amount.currency !== mandate.currency) deny.push(`devise ${request.amount.currency} hors mandat (${mandate.currency})`);
28
+ if (!mandate.allowedTypes.includes(request.type)) deny.push(`type ${request.type} non autorisé`);
29
+ if (mandate.allowedCounterparties.length && !mandate.allowedCounterparties.includes(request.counterparty))
30
+ deny.push(`bénéficiaire ${request.counterparty} hors liste`);
31
+ if (!deny.length) {
32
+ if (request.amount.minor > mandate.maxPerPayment.minor) deny.push('dépasse le maximum par paiement');
33
+ const after = add(spentToday || money(0n, mandate.currency, { minor: true }), request.amount);
34
+ if (after.minor > mandate.maxPerDay.minor) deny.push('dépasse le plafond du jour');
35
+ if (mandate.humanApprovalAbove && request.amount.minor > mandate.humanApprovalAbove.minor) human.push('au-dessus du seuil de validation humaine');
36
+ }
37
+ const decision = deny.length ? 'DENY' : human.length ? 'NEEDS_HUMAN' : 'ALLOW';
38
+ return { decision, reasons: [...deny, ...human],
39
+ audit: { at: now.toISOString(), mandateId: mandate.id, agentId: mandate.agentId, purpose: mandate.purpose,
40
+ counterparty: request.counterparty, type: request.type, amount: `${request.amount.minor} ${request.amount.currency}`,
41
+ idempotencyKey: request.idempotencyKey || null, decision } };
42
+ }
package/src/money.mjs ADDED
@@ -0,0 +1,75 @@
1
+ // Argent exact, toutes devises. Entiers (BigInt) en unités mineures, jamais de float.
2
+ // XAF/XOF : 0 décimale. USD/EUR : 2. Stablecoins (USDC/USDT) : 6.
3
+
4
+ export const EXPONENTS = Object.freeze({
5
+ XAF: 0, XOF: 0, UGX: 0, RWF: 0, GNF: 0, KMF: 0,
6
+ NGN: 2, KES: 2, GHS: 2, TZS: 2, ZAR: 2, MAD: 2, EGP: 2, CDF: 2, ZMW: 2,
7
+ USD: 2, EUR: 2, GBP: 2, CAD: 2,
8
+ USDC: 6, USDT: 6,
9
+ });
10
+
11
+ export function exponentOf(currency) {
12
+ const e = EXPONENTS[currency];
13
+ if (e === undefined) throw new Error(`Devise inconnue : ${currency}. Ajoute-la à EXPONENTS avec son nombre de décimales.`);
14
+ return e;
15
+ }
16
+
17
+ // money("5000", "XAF") ; money("12.50", "USD") ; money(5000n, "XAF", { minor: true })
18
+ export function money(amount, currency, { minor = false } = {}) {
19
+ const exp = exponentOf(currency);
20
+ if (minor) {
21
+ const v = BigInt(amount);
22
+ if (v < 0n) throw new Error('Montant négatif interdit');
23
+ return Object.freeze({ minor: v, currency });
24
+ }
25
+ const s = String(amount).trim();
26
+ const m = /^(\d+)(?:\.(\d+))?$/.exec(s);
27
+ if (!m) throw new Error(`Montant invalide : "${s}" (attendu : chiffres, point décimal facultatif)`);
28
+ const frac = m[2] || '';
29
+ if (frac.length > exp) throw new Error(`${currency} accepte ${exp} décimale(s), reçu "${s}"`);
30
+ return Object.freeze({ minor: BigInt(m[1] + frac.padEnd(exp, '0')), currency });
31
+ }
32
+
33
+ export function toDecimal(m) {
34
+ const exp = exponentOf(m.currency), s = m.minor.toString().padStart(exp + 1, '0');
35
+ return exp === 0 ? s : `${s.slice(0, -exp)}.${s.slice(-exp)}`;
36
+ }
37
+
38
+ const same = (a, b) => { if (a.currency !== b.currency) throw new Error(`Devises différentes : ${a.currency} / ${b.currency}`); };
39
+ export const add = (a, b) => (same(a, b), money(a.minor + b.minor, a.currency, { minor: true }));
40
+ export const sub = (a, b) => { same(a, b); if (b.minor > a.minor) throw new Error('Résultat négatif'); return money(a.minor - b.minor, a.currency, { minor: true }); };
41
+ export const equals = (a, b) => a.currency === b.currency && a.minor === b.minor;
42
+
43
+ // Répartition exacte : la somme des parts est toujours égale au total.
44
+ export function split(m, parts) {
45
+ const weights = Array.isArray(parts) ? parts.map(BigInt) : Array(parts).fill(1n);
46
+ const total = weights.reduce((s, w) => s + w, 0n);
47
+ if (total <= 0n) throw new Error('Poids invalides');
48
+ const shares = weights.map(w => (m.minor * w) / total);
49
+ let rest = m.minor - shares.reduce((s, x) => s + x, 0n);
50
+ for (let i = 0; rest > 0n; i = (i + 1) % shares.length, rest--) shares[i]++;
51
+ return shares.map(v => money(v, m.currency, { minor: true }));
52
+ }
53
+
54
+ // Conversion avec un taux écrit en décimal ("655.957" = 1 EUR -> 655,957 XAF). Arrondi explicite.
55
+ export function convert(m, to, rate, rounding = 'half-up') {
56
+ const r = /^(\d+)(?:\.(\d+))?$/.exec(String(rate));
57
+ if (!r) throw new Error(`Taux invalide : ${rate}`);
58
+ const num = BigInt(r[1] + (r[2] || '')), den = 10n ** BigInt((r[2] || '').length);
59
+ const n = m.minor * num * 10n ** BigInt(exponentOf(to));
60
+ const d = den * 10n ** BigInt(exponentOf(m.currency));
61
+ let q = n / d;
62
+ const rem = n % d;
63
+ if (rem !== 0n && (rounding === 'up' || (rounding === 'half-up' && rem * 2n >= d))) q++;
64
+ return money(q, to, { minor: true });
65
+ }
66
+
67
+ // Écart relatif en points de base (1 bp = 0,01 %) entre deux montants de même devise.
68
+ export function driftBps(expected, actual) {
69
+ same(expected, actual);
70
+ if (expected.minor === 0n) return actual.minor === 0n ? 0 : Infinity;
71
+ const diff = actual.minor > expected.minor ? actual.minor - expected.minor : expected.minor - actual.minor;
72
+ return Number((diff * 10000n) / expected.minor);
73
+ }
74
+
75
+ export const format = m => `${toDecimal(m)} ${m.currency}`;
@@ -0,0 +1,91 @@
1
+ // Le modèle de paiement Kinyan, aligné sur le standard GSMA Mobile Money API :
2
+ // - id = clientCorrelationId (X-CorrelationID) : créé AVANT l'appel, réutilisé à chaque réessai
3
+ // - serverCorrelationId / transactionReference : références du fournisseur
4
+ // - debitParty / creditParty : listes { key, value } (msisdn, walletid, accountid…)
5
+ // - trois montants : demandé, confirmé par le fournisseur, réglé (voir ledger.mjs)
6
+ import crypto from 'node:crypto';
7
+ import { money, equals } from './money.mjs';
8
+
9
+ export const TYPES = ['merchantpay', 'billpay', 'disbursement', 'transfer', 'inttransfer', 'reversal'];
10
+
11
+ // Transitions autorisées. Tout le reste est refusé.
12
+ const ALLOWED = {
13
+ CREATED: ['PENDING', 'UNKNOWN', 'PAID', 'FAILED', 'NEEDS_REVIEW'],
14
+ PENDING: ['PAID', 'FAILED', 'EXPIRED', 'NEEDS_REVIEW'],
15
+ UNKNOWN: ['PENDING', 'PAID', 'FAILED', 'EXPIRED', 'NEEDS_REVIEW'],
16
+ EXPIRED: ['NEEDS_REVIEW'],
17
+ NEEDS_REVIEW: ['PAID', 'FAILED', 'REVERSED'],
18
+ PAID: ['REVERSED'],
19
+ FAILED: [],
20
+ REVERSED: [],
21
+ };
22
+ export const FINAL = ['PAID', 'FAILED', 'REVERSED'];
23
+ export const OPEN = ['CREATED', 'PENDING', 'UNKNOWN'];
24
+
25
+ export function createPayment({ type = 'merchantpay', amount, debitParty = [], creditParty = [], quote = null, metadata = {}, id } = {}) {
26
+ if (!TYPES.includes(type)) throw new Error(`Type inconnu : ${type}`);
27
+ if (!amount?.currency) throw new Error('amount doit être créé avec money()');
28
+ if (amount.minor <= 0n) throw new Error('Montant nul interdit');
29
+ return {
30
+ id: id || crypto.randomUUID(), // = clientCorrelationId GSMA
31
+ type, status: 'CREATED',
32
+ requested: amount, confirmed: null, settlements: [],
33
+ debitParty, creditParty, quote, metadata,
34
+ provider: { name: null, serverCorrelationId: null, transactionReference: null },
35
+ history: [{ at: new Date().toISOString(), from: null, to: 'CREATED', reason: 'création' }],
36
+ effects: 0,
37
+ };
38
+ }
39
+
40
+ // Change l'état seulement si la transition est permise. Retourne true si l'état a changé.
41
+ export function transition(p, to, reason) {
42
+ if (!(ALLOWED[p.status] || []).includes(to)) return false;
43
+ p.history.push({ at: new Date().toISOString(), from: p.status, to, reason });
44
+ p.status = to;
45
+ return true;
46
+ }
47
+
48
+ // Statut normalisé d'un fournisseur : { status: 'pending'|'completed'|'failed', amount: money|null, reference }
49
+ // RÈGLE : n'appeler qu'avec un statut RELU chez le fournisseur, jamais avec le corps d'une notification.
50
+ // Retourne 'FULFIL' quand l'appli doit livrer — une seule fois dans la vie du paiement.
51
+ export function applyProviderStatus(p, remote) {
52
+ if (remote.reference && !p.provider.transactionReference) p.provider.transactionReference = remote.reference;
53
+ // Tant que le paiement n'est pas confirmé, un montant 0 veut dire « pas encore connu » (vu chez CamPay) :
54
+ // on ne compare les montants qu'à partir du moment où il y a un vrai montant ou une confirmation.
55
+ const amountKnown = remote.amount && (remote.amount.minor !== 0n || remote.status === 'completed');
56
+ if (amountKnown && !equals(remote.amount, p.requested)) {
57
+ transition(p, 'NEEDS_REVIEW', `montant fournisseur ${remote.amount.minor} ${remote.amount.currency} ≠ demandé`);
58
+ return null;
59
+ }
60
+ if (remote.status === 'completed') {
61
+ p.confirmed = remote.amount || p.requested;
62
+ if (transition(p, 'PAID', 'confirmé par le fournisseur')) { p.effects++; return 'FULFIL'; }
63
+ transition(p, 'NEEDS_REVIEW', 'succès arrivé après expiration');
64
+ return null;
65
+ }
66
+ if (remote.status === 'failed') { transition(p, 'FAILED', 'refusé par le fournisseur'); return null; }
67
+ if (remote.status === 'pending') transition(p, 'PENDING', 'en attente chez le fournisseur');
68
+ return null;
69
+ }
70
+
71
+ // Appel réseau incertain (timeout, coupure, 5xx) : on ne sait pas. Jamais FAILED.
72
+ export const markUnknown = (p, why = 'réponse perdue') => transition(p, 'UNKNOWN', why);
73
+
74
+ // Expiration : à appeler APRÈS avoir relu le statut chez le fournisseur.
75
+ export const expire = (p, why = 'délai dépassé, toujours en attente après relecture') => transition(p, 'EXPIRED', why);
76
+
77
+ export function normalizeStatus(raw) {
78
+ const s = String(raw || '').toLowerCase();
79
+ if (/(complet|success|succe|paid|approved)/.test(s)) return 'completed';
80
+ if (/(fail|declin|reject|cancel|expired|error)/.test(s)) return 'failed';
81
+ return 'pending';
82
+ }
83
+
84
+ // Les fournisseurs écrivent parfois « 100.00 » même pour le FCFA (0 décimale) : on retire seulement des zéros
85
+ // inutiles. « 100.50 » en FCFA reste une erreur, car ce n'est pas un montant FCFA valide.
86
+ export const amountFrom = (value, currency) => {
87
+ if (value == null || value === '' || !currency) return null;
88
+ let s = String(value).trim();
89
+ if (s.includes('.')) s = s.replace(/0+$/, '').replace(/\.$/, '');
90
+ return money(s, currency);
91
+ };
package/src/verify.mjs ADDED
@@ -0,0 +1,96 @@
1
+ // « Vérifie avant de livrer » : le marchand ne croit ni la capture d'écran, ni le SMS montré par le client.
2
+ // Il demande à SON fournisseur de paiement. Trois réponses possibles, pensées pour un vendeur pressé :
3
+ // LIVRER — l'argent est arrivé sur ton compte, au bon montant, et cette référence n'a jamais servi
4
+ // ATTENDRE — paiement en cours, ou on n'arrive pas à joindre le fournisseur : ne donne rien pour l'instant
5
+ // NE_PAS_LIVRER — pas de paiement, paiement échoué, mauvais montant, ou référence déjà utilisée
6
+ // Règle d'or : en cas de doute ou de panne, on ne dit JAMAIS « LIVRER » (fail closed).
7
+ import fs from 'node:fs';
8
+ import { money, toDecimal, format } from './money.mjs';
9
+
10
+ export const VERDICTS = Object.freeze({ LIVRER: 'LIVRER', ATTENDRE: 'ATTENDRE', NE_PAS_LIVRER: 'NE_PAS_LIVRER' });
11
+
12
+ // Registre des références déjà « encaissées » : empêche de montrer deux fois le même vrai reçu.
13
+ // claim() est synchrone (vérifier + écrire sans await entre les deux) : sûr dans un seul processus Node.
14
+ // Plusieurs serveurs ou caisses sur des machines différentes -> base de données avec contrainte UNIQUE.
15
+ export function memoryStore() {
16
+ const used = new Map();
17
+ return { get: ref => used.get(ref) ?? null, claim(ref, info) { if (used.has(ref)) return false; used.set(ref, info); return true; } };
18
+ }
19
+
20
+ export function fileStore(path) {
21
+ let used = {};
22
+ try { used = JSON.parse(fs.readFileSync(path, 'utf8')); } catch (e) { if (e.code !== 'ENOENT') throw e; }
23
+ return {
24
+ get: ref => used[ref] ?? null,
25
+ claim(ref, info) {
26
+ if (used[ref]) return false;
27
+ used[ref] = info;
28
+ const tmp = `${path}.tmp`;
29
+ fs.writeFileSync(tmp, JSON.stringify(used, null, 2));
30
+ fs.renameSync(tmp, path); // écriture atomique : pas de fichier à moitié écrit
31
+ return true;
32
+ },
33
+ };
34
+ }
35
+
36
+ const clean = ref => String(ref ?? '').trim();
37
+ // Clé du registre : majuscules, sans espaces ni tirets. « mp-12 34 » et « MP1234 » sont le MÊME reçu.
38
+ const keyOf = ref => clean(ref).toUpperCase().replace(/[\s\-_.]/g, '');
39
+
40
+ export function createVerifier({ provider, store = memoryStore(), maxAgeHours = 72, now = () => Date.now() }) {
41
+ if (!provider?.lookup) throw new Error('Le fournisseur doit savoir lire un paiement (lookup)');
42
+ const no = (raison, extra = {}) => ({ verdict: VERDICTS.NE_PAS_LIVRER, raison, ...extra });
43
+
44
+ return {
45
+ async check({ reference, expectedAmount, currency = 'XAF', cashier = null }) {
46
+ const ref = clean(reference);
47
+ if (ref.length < 4) return no('Référence vide ou trop courte. Demande au client la référence de son reçu.');
48
+ let expected;
49
+ try { expected = money(String(expectedAmount), currency); } catch { return no('Montant attendu invalide.'); }
50
+
51
+ const key = keyOf(ref);
52
+ const already = store.get(key);
53
+ if (already) return no(`Cette référence a déjà servi le ${new Date(already.at).toLocaleString('fr-FR')}. Un même reçu ne paie qu'une fois.`, { deja: already });
54
+
55
+ let t;
56
+ try { t = await provider.lookup(ref); }
57
+ catch { return { verdict: VERDICTS.ATTENDRE, raison: 'Impossible de joindre le service de paiement. Ne livre pas encore, réessaie dans une minute.' }; }
58
+
59
+ if (!t) return no("Aucun paiement avec cette référence sur TON compte. La capture ou le SMS montré n'est pas une preuve.");
60
+ if (t.status === 'failed') return no(`Le paiement a échoué ou a été annulé (${t.rawStatus ?? 'échec'}).`);
61
+ if (t.status !== 'completed') return { verdict: VERDICTS.ATTENDRE, raison: "Le client n'a pas encore validé avec son code. Attends la confirmation, puis vérifie à nouveau." };
62
+ if (!t.amount) return no('Le service ne donne pas le montant : vérification impossible.');
63
+ if (t.amount.currency !== expected.currency) return no(`Devise différente : reçu ${format(t.amount)}, attendu ${format(expected)}.`);
64
+ if (t.amount.minor < expected.minor) return no(`Montant insuffisant : reçu ${format(t.amount)}, attendu ${format(expected)}.`, { recu: toDecimal(t.amount) });
65
+
66
+ const when = Date.parse(t.completedAt || t.createdAt || '');
67
+ if (Number.isFinite(when) && now() - when > maxAgeHours * 3600_000)
68
+ return no(`Paiement trop ancien (${new Date(when).toLocaleDateString('fr-FR')}). Un vieux reçu peut être réutilisé : demande un nouveau paiement.`);
69
+
70
+ // Dernière barrière : on « consomme » la référence. Si une autre caisse l'a prise entre-temps, on refuse.
71
+ const info = { at: new Date(now()).toISOString(), montant: toDecimal(t.amount), devise: t.amount.currency, caisse: cashier };
72
+ if (!store.claim(key, info)) return no('Cette référence vient juste d\'être utilisée à une autre caisse.');
73
+ const plus = t.amount.minor > expected.minor ? ` (le client a payé ${format(t.amount)}, plus que prévu)` : '';
74
+ return { verdict: VERDICTS.LIVRER, raison: `Argent bien reçu sur ton compte : ${format(t.amount)}${plus}.`, recu: toDecimal(t.amount) };
75
+ },
76
+ };
77
+ }
78
+
79
+ // Faux fournisseur pour essayer l'outil sans compte ni clé. Références de démonstration :
80
+ // DEMO-OK-5000 (payé 5000), DEMO-ATTENTE, DEMO-ECHEC, DEMO-VIEUX (payé il y a 10 jours), tout le reste = inconnu
81
+ export function demoProvider({ now = () => Date.now() } = {}) {
82
+ const table = {
83
+ 'DEMO-OK-5000': { status: 'completed', rawStatus: 'complete', amount: money('5000', 'XAF'), completedAt: () => new Date(now()).toISOString() },
84
+ 'DEMO-OK-15000': { status: 'completed', rawStatus: 'complete', amount: money('15000', 'XAF'), completedAt: () => new Date(now()).toISOString() },
85
+ 'DEMO-ATTENTE': { status: 'pending', rawStatus: 'pending', amount: money('5000', 'XAF') },
86
+ 'DEMO-ECHEC': { status: 'failed', rawStatus: 'failed', amount: money('5000', 'XAF') },
87
+ 'DEMO-VIEUX': { status: 'completed', rawStatus: 'complete', amount: money('5000', 'XAF'), completedAt: () => new Date(now() - 10 * 86400_000).toISOString() },
88
+ };
89
+ return {
90
+ name: 'demo',
91
+ async lookup(ref) {
92
+ const t = table[ref.toUpperCase()];
93
+ return t ? { ...t, reference: ref, completedAt: t.completedAt?.() ?? null } : null;
94
+ },
95
+ };
96
+ }