@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,112 @@
1
+ // Intégration CamPay ROBUSTE (exemple de référence). Parle le format CamPay : elle fonctionnerait
2
+ // contre la vraie API en changeant seulement CAMPAY_URL et les identifiants. En mémoire pour la démo.
3
+ import http from 'node:http';
4
+ import crypto from 'node:crypto';
5
+
6
+ const CAMPAY = process.env.CAMPAY_URL || 'http://localhost:4010'; // demo.campay.net en vrai
7
+ const USER = process.env.CAMPAY_USERNAME || 'app_user', PASS = process.env.CAMPAY_PASSWORD || 'app_pass';
8
+ const WKEY = process.env.CAMPAY_WEBHOOK_KEY || 'campay_webhook_key', PORT = Number(process.env.PORT || 4031);
9
+ const payments = new Map(), byOrder = new Map(), effects = new Map();
10
+ const OPEN = ['CREATED', 'PENDING', 'UNKNOWN'];
11
+
12
+ // ---- Authentification : jeton mis en cache, renouvelé avant expiration ou sur 401 ----
13
+ let token = null, tokenExp = 0;
14
+ async function auth(force = false) {
15
+ if (!force && token && Date.now() < tokenExp - 30_000) return token;
16
+ const r = await fetch(`${CAMPAY}/api/token/`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: USER, password: PASS }) });
17
+ const j = await r.json(); token = j.token; tokenExp = Date.now() + j.expires_in * 1000; return token;
18
+ }
19
+ async function api(method, path, body) {
20
+ for (const retry of [false, true]) {
21
+ const r = await fetch(CAMPAY + path, { method, headers: { 'content-type': 'application/json', authorization: `Token ${await auth(retry)}` },
22
+ body: body ? JSON.stringify(body) : undefined });
23
+ if (r.status === 401 && !retry) continue; // 401 = rien n'a été créé : relancer est sûr
24
+ return r;
25
+ }
26
+ }
27
+
28
+ // ---- Machine à états ----
29
+ function transition(p, from, to) {
30
+ if (!from.includes(p.status)) return false;
31
+ p.status = to;
32
+ if (to === 'PAID') effects.set(p.orderId, (effects.get(p.orderId) || 0) + 1);
33
+ return true;
34
+ }
35
+ function apply(p, remote) {
36
+ const amount = Number(remote.amount);
37
+ if (!Number.isSafeInteger(amount) || amount !== p.amount || remote.currency !== p.currency) return transition(p, [...OPEN, 'EXPIRED'], 'NEEDS_REVIEW');
38
+ if (remote.status === 'SUCCESSFUL') return transition(p, OPEN, 'PAID') || transition(p, ['EXPIRED'], 'NEEDS_REVIEW');
39
+ if (remote.status === 'FAILED') return transition(p, OPEN, 'FAILED');
40
+ if (remote.status === 'PENDING') return transition(p, ['CREATED', 'UNKNOWN'], 'PENDING');
41
+ }
42
+ async function resolve(p) {
43
+ try {
44
+ if (p.reference) { const r = await api('GET', `/api/transaction/${p.reference}/`); if (r.status === 200) apply(p, await r.json()); return; }
45
+ // Pas de référence (réponse perdue) : chercher notre external_reference dans l'historique.
46
+ // On NE relance JAMAIS la collecte : CamPay ne garantit pas le refus des doublons.
47
+ const r = await api('POST', '/api/history/', {});
48
+ const hit = r.status === 200 ? (await r.json()).data?.find(t => t.external_reference === p.id) : null;
49
+ if (hit) { p.reference = hit.reference; apply(p, hit); }
50
+ } catch { }
51
+ }
52
+ async function collect(p) {
53
+ p.inflight = true;
54
+ try {
55
+ const r = await api('POST', '/api/collect/', { amount: String(p.amount), currency: p.currency, from: p.phone,
56
+ description: `Commande ${p.orderId}`, external_reference: p.id });
57
+ if (r.status === 200) { p.reference = (await r.json()).reference; transition(p, ['CREATED', 'UNKNOWN'], 'PENDING'); }
58
+ else transition(p, ['CREATED'], 'FAILED'); // refus explicite (numéro, montant) : rien n'a été débité
59
+ } catch { transition(p, ['CREATED'], 'UNKNOWN'); } // timeout ≠ échec
60
+ finally { p.inflight = false; }
61
+ }
62
+
63
+ // ---- Vérification de la signature de notification (JWT HS256, clé webhook de l'application) ----
64
+ function validSignature(jwt) {
65
+ const parts = String(jwt || '').split('.'); if (parts.length !== 3) return false;
66
+ try { if (JSON.parse(Buffer.from(parts[0], 'base64url')).alg !== 'HS256') return false; } catch { return false; }
67
+ const expected = crypto.createHmac('sha256', WKEY).update(`${parts[0]}.${parts[1]}`).digest();
68
+ const got = Buffer.from(parts[2], 'base64url');
69
+ return got.length === expected.length && crypto.timingSafeEqual(got, expected);
70
+ }
71
+
72
+ const read = req => new Promise(r => { let b = ''; req.on('data', c => b += c); req.on('end', () => r(b)); });
73
+ const send = (res, c, o) => { res.writeHead(c, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); };
74
+
75
+ http.createServer(async (req, res) => {
76
+ const url = new URL(req.url, 'http://x'), path = url.pathname;
77
+
78
+ if (req.method === 'POST' && path === '/pay') {
79
+ const { orderId, amount, phone } = JSON.parse(await read(req));
80
+ if (!Number.isSafeInteger(amount) || amount <= 0) return send(res, 400, { error: 'montant invalide' });
81
+ let p = payments.get(byOrder.get(orderId));
82
+ if (!p) {
83
+ p = { id: crypto.randomUUID(), orderId, amount, currency: 'XAF', phone, status: 'CREATED', reference: null };
84
+ payments.set(p.id, p); byOrder.set(orderId, p.id); // réservation avant l'appel (SQL : INSERT ... ON CONFLICT DO NOTHING)
85
+ await collect(p);
86
+ } else if (!p.inflight && ['CREATED', 'UNKNOWN'].includes(p.status)) await resolve(p);
87
+ return send(res, 202, { status: p.status });
88
+ }
89
+
90
+ if (path === '/webhook') { // CamPay appelle l'URL configurée dans le tableau de bord
91
+ const q = Object.fromEntries(url.searchParams);
92
+ if (!validSignature(q.signature)) return send(res, 401, {});
93
+ const p = payments.get(q.external_reference) || [...payments.values()].find(x => x.reference === q.reference);
94
+ if (p) { if (!p.reference && q.external_reference === p.id) p.reference = q.reference; await resolve(p); }
95
+ return send(res, 200, {});
96
+ }
97
+
98
+ if (req.method === 'POST' && path === '/_test/reconcile') {
99
+ await Promise.all([...payments.values()].filter(p => OPEN.includes(p.status) || p.status === 'EXPIRED').map(resolve));
100
+ return send(res, 200, {});
101
+ }
102
+ if (req.method === 'POST' && path === '/_test/force-expiry') {
103
+ for (const p of [...payments.values()].filter(x => OPEN.includes(x.status))) { await resolve(p); transition(p, OPEN, 'EXPIRED'); }
104
+ return send(res, 200, {});
105
+ }
106
+ if (req.method === 'GET' && path.startsWith('/orders/')) {
107
+ const p = payments.get(byOrder.get(decodeURIComponent(path.split('/').pop())));
108
+ return send(res, 200, { status: p ? p.status : 'INCONNU' });
109
+ }
110
+ if (req.method === 'GET' && path.startsWith('/_test/effects/')) return send(res, 200, { count: effects.get(decodeURIComponent(path.split('/').pop())) || 0 });
111
+ send(res, 404, {});
112
+ }).listen(PORT, () => console.log(`Intégration CamPay robuste sur http://localhost:${PORT}`));
@@ -0,0 +1,13 @@
1
+ {
2
+ "provider": { "port": 4010, "dialect": "campay", "username": "app_user", "password": "app_pass",
3
+ "webhookKey": "campay_webhook_key", "webhookUrl": "http://localhost:4030/webhook", "tokenTtlSec": 3600 },
4
+ "merchant": {
5
+ "payUrl": "http://localhost:4030/pay",
6
+ "orderUrl": "http://localhost:4030/orders/{orderId}",
7
+ "reconcileUrl": "http://localhost:4030/_test/reconcile",
8
+ "forceExpiryUrl": "http://localhost:4030/_test/force-expiry",
9
+ "effectsUrl": "http://localhost:4030/_test/effects/{orderId}"
10
+ },
11
+ "report": "exemples/rapport-campay-naif.md",
12
+ "badge": "exemples/badge-campay-naif.svg"
13
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "provider": { "port": 4010, "dialect": "campay", "username": "app_user", "password": "app_pass",
3
+ "webhookKey": "campay_webhook_key", "webhookUrl": "http://localhost:4031/webhook", "tokenTtlSec": 3600 },
4
+ "merchant": {
5
+ "payUrl": "http://localhost:4031/pay",
6
+ "orderUrl": "http://localhost:4031/orders/{orderId}",
7
+ "reconcileUrl": "http://localhost:4031/_test/reconcile",
8
+ "forceExpiryUrl": "http://localhost:4031/_test/force-expiry",
9
+ "effectsUrl": "http://localhost:4031/_test/effects/{orderId}"
10
+ },
11
+ "report": "exemples/rapport-campay-robuste.md",
12
+ "badge": "exemples/badge-campay-robuste.svg"
13
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "provider": { "port": 4010, "secret": "whsec_test", "apiKey": "test_key" },
3
+ "merchant": {
4
+ "payUrl": "http://localhost:4020/pay",
5
+ "orderUrl": "http://localhost:4020/orders/{orderId}",
6
+ "reconcileUrl": "http://localhost:4020/_test/reconcile",
7
+ "forceExpiryUrl": "http://localhost:4020/_test/force-expiry",
8
+ "effectsUrl": "http://localhost:4020/_test/effects/{orderId}",
9
+ "paidStates": ["PAID"],
10
+ "reviewStates": ["NEEDS_REVIEW"]
11
+ },
12
+ "report": "exemples/rapport-naif.md"
13
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "provider": { "port": 4010, "secret": "whsec_test", "apiKey": "test_key" },
3
+ "merchant": {
4
+ "payUrl": "http://localhost:4021/pay",
5
+ "orderUrl": "http://localhost:4021/orders/{orderId}",
6
+ "reconcileUrl": "http://localhost:4021/_test/reconcile",
7
+ "forceExpiryUrl": "http://localhost:4021/_test/force-expiry",
8
+ "effectsUrl": "http://localhost:4021/_test/effects/{orderId}",
9
+ "paidStates": ["PAID"],
10
+ "reviewStates": ["NEEDS_REVIEW"]
11
+ },
12
+ "report": "exemples/rapport-robuste.md"
13
+ }
@@ -0,0 +1,27 @@
1
+ # À copier dans .github/workflows/crash-test.yml de ton projet.
2
+ # Bloque la fusion d'une pull request si l'intégration de paiement casse sous les pannes.
3
+ name: Crash-test paiements
4
+ on: [pull_request]
5
+ jobs:
6
+ crash-test:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v4
10
+ - uses: actions/setup-node@v4
11
+ with: { node-version: 20 }
12
+ - name: Récupérer le crash-test
13
+ run: git clone --depth 1 https://github.com/<ton-compte>/fintech-cemac /tmp/fintech-cemac
14
+ - name: Démarrer l'appli en mode test, branchée sur le simulateur
15
+ env:
16
+ CAMPAY_URL: http://localhost:4010 # l'appli appelle le simulateur au lieu de CamPay
17
+ CAMPAY_USERNAME: app_user
18
+ CAMPAY_PASSWORD: app_pass
19
+ CAMPAY_WEBHOOK_KEY: campay_webhook_key
20
+ run: |
21
+ npm ci && npm start &
22
+ for i in $(seq 1 30); do curl -sf http://localhost:3000/health && break; sleep 1; done
23
+ - name: Lancer le crash-test
24
+ run: node /tmp/fintech-cemac/tools/chaos/chaos.mjs crash-test.json
25
+ - uses: actions/upload-artifact@v4
26
+ if: always()
27
+ with: { name: rapport-crash-test, path: chaos-report.md }
@@ -0,0 +1,47 @@
1
+ // Appli marchande NAÏVE : le code « qui marche en démo ». Sert à montrer ce que le simulateur détecte.
2
+ // NE PAS COPIER. Chaque commentaire ❌ correspond à une faille réelle courante.
3
+ import http from 'node:http';
4
+
5
+ const SIM = process.env.SIM_URL || 'http://localhost:4010', KEY = process.env.API_KEY || 'test_key';
6
+ const PORT = Number(process.env.PORT || 4020), SELF = `http://localhost:${PORT}`;
7
+ const orders = new Map(), byRef = new Map(), effects = new Map();
8
+
9
+ const read = req => new Promise(r => { let b = ''; req.on('data', c => b += c); req.on('end', () => r(b)); });
10
+ const send = (res, c, o) => { res.writeHead(c, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); };
11
+
12
+ http.createServer(async (req, res) => {
13
+ const path = new URL(req.url, 'http://x').pathname;
14
+
15
+ if (req.method === 'POST' && path === '/pay') {
16
+ const { orderId, amount, phone } = JSON.parse(await read(req));
17
+ const o = orders.get(orderId);
18
+ if (o && o.status === 'PAID') return send(res, 200, o); // ❌ vérifier puis agir, sans verrou
19
+ try {
20
+ const r = await fetch(`${SIM}/v1/collect`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-api-key': KEY },
21
+ body: JSON.stringify({ amount, currency: 'XAF', phone, callback_url: `${SELF}/webhook` }) }); // ❌ pas d'identifiant idempotent
22
+ const j = await r.json();
23
+ orders.set(orderId, { orderId, amount, status: 'PENDING', reference: j.reference });
24
+ byRef.set(j.reference, orderId);
25
+ return send(res, 202, { status: 'PENDING' });
26
+ } catch { return send(res, 502, { error: 'Erreur, réessayez' }); } // ❌ timeout traité comme un échec
27
+ }
28
+
29
+ if (req.method === 'POST' && path === '/webhook') {
30
+ const b = JSON.parse(await read(req)); // ❌ aucune vérification de signature
31
+ const o = orders.get(byRef.get(b.reference));
32
+ if (o) {
33
+ if (b.status === 'SUCCESSFUL') { o.status = 'PAID'; effects.set(o.orderId, (effects.get(o.orderId) || 0) + 1); } // ❌ on croit le message, effet répété
34
+ if (b.status === 'FAILED') o.status = 'FAILED'; // ❌ un état final peut changer
35
+ }
36
+ return send(res, 200, {});
37
+ }
38
+
39
+ if (req.method === 'POST' && (path === '/_test/reconcile' || path === '/_test/force-expiry')) {
40
+ for (const o of orders.values()) if (o.status === 'PENDING') o.status = 'EXPIRED'; // ❌ « en attente trop longtemps = échoué »
41
+ return send(res, 200, {});
42
+ }
43
+
44
+ if (req.method === 'GET' && path.startsWith('/orders/')) return send(res, 200, orders.get(decodeURIComponent(path.split('/').pop())) || { status: 'INCONNU' });
45
+ if (req.method === 'GET' && path.startsWith('/_test/effects/')) return send(res, 200, { count: effects.get(decodeURIComponent(path.split('/').pop())) || 0 });
46
+ send(res, 404, {});
47
+ }).listen(PORT, () => console.log(`Marchand naïf sur ${SELF}`));
@@ -0,0 +1,101 @@
1
+ // Appli marchande ROBUSTE : applique les 7 règles. En mémoire pour la démo ; en production,
2
+ // chaque « réservation » ci-dessous est une requête SQL atomique (INSERT ... ON CONFLICT DO NOTHING, UPDATE ... WHERE status IN (...)).
3
+ import http from 'node:http';
4
+ import crypto from 'node:crypto';
5
+
6
+ const SIM = process.env.SIM_URL || 'http://localhost:4010', KEY = process.env.API_KEY || 'test_key';
7
+ const SECRET = process.env.SECRET || 'whsec_test', PORT = Number(process.env.PORT || 4021), SELF = `http://localhost:${PORT}`;
8
+ const payments = new Map(), byOrder = new Map(), effects = new Map();
9
+ const OPEN = ['CREATED', 'PENDING', 'UNKNOWN'];
10
+
11
+ const H = { 'content-type': 'application/json', 'x-api-key': KEY };
12
+ const read = req => new Promise(r => { let b = ''; req.on('data', c => b += c); req.on('end', () => r(b)); });
13
+ const send = (res, c, o) => { res.writeHead(c, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); };
14
+
15
+ // Transition conditionnelle : ne change l'état que s'il est dans `from` (règle 6). Synchrone = atomique en Node.
16
+ function transition(p, from, to) {
17
+ if (!from.includes(p.status)) return false;
18
+ p.status = to;
19
+ if (to === 'PAID') effects.set(p.orderId, (effects.get(p.orderId) || 0) + 1); // effet métier une seule fois
20
+ return true;
21
+ }
22
+
23
+ // Appliquer un statut LU chez le fournisseur (jamais celui d'un message reçu).
24
+ function apply(p, remote) {
25
+ if (!p.reference) p.reference = remote.reference;
26
+ if (remote.amount !== p.amount || remote.currency !== p.currency) return transition(p, [...OPEN, 'EXPIRED'], 'NEEDS_REVIEW');
27
+ if (remote.status === 'SUCCESSFUL') return transition(p, OPEN, 'PAID') || transition(p, ['EXPIRED'], 'NEEDS_REVIEW');
28
+ if (remote.status === 'FAILED') return transition(p, OPEN, 'FAILED');
29
+ if (remote.status === 'PENDING') return transition(p, ['CREATED', 'UNKNOWN'], 'PENDING');
30
+ }
31
+
32
+ async function readRemote(p) {
33
+ const url = p.reference ? `${SIM}/v1/transactions/${p.reference}` : `${SIM}/v1/transactions?external_reference=${p.id}`;
34
+ const r = await fetch(url, { headers: H });
35
+ return r.status === 200 ? r.json() : null;
36
+ }
37
+
38
+ async function collect(p) {
39
+ p.inflight = true;
40
+ try {
41
+ const r = await fetch(`${SIM}/v1/collect`, { method: 'POST', headers: H, body: JSON.stringify({ amount: p.amount, currency: p.currency,
42
+ phone: p.phone, external_reference: p.id, callback_url: `${SELF}/webhook` }) }); // p.id = identifiant idempotent (règle 2)
43
+ const j = await r.json();
44
+ if (r.status === 202) { p.reference = j.reference; transition(p, ['CREATED', 'UNKNOWN'], 'PENDING'); }
45
+ else if (r.status === 409) await resolve(p);
46
+ } catch { transition(p, ['CREATED'], 'UNKNOWN'); } // timeout ≠ échec : on ne sait pas
47
+ finally { p.inflight = false; }
48
+ }
49
+
50
+ async function resolve(p) { // résoudre un statut incertain
51
+ try { const remote = await readRemote(p); if (remote) apply(p, remote); } catch { }
52
+ }
53
+
54
+ http.createServer(async (req, res) => {
55
+ const path = new URL(req.url, 'http://x').pathname;
56
+
57
+ if (req.method === 'POST' && path === '/pay') {
58
+ const { orderId, amount, phone } = JSON.parse(await read(req));
59
+ if (!Number.isSafeInteger(amount) || amount <= 0) return send(res, 400, { error: 'montant invalide' });
60
+ let p = payments.get(byOrder.get(orderId));
61
+ if (!p) { // réservation atomique AVANT l'appel (faille 1)
62
+ p = { id: crypto.randomUUID(), orderId, amount, currency: 'XAF', phone, status: 'CREATED', reference: null };
63
+ payments.set(p.id, p); byOrder.set(orderId, p.id);
64
+ await collect(p);
65
+ } else if (!p.inflight && ['CREATED', 'UNKNOWN'].includes(p.status)) {
66
+ await resolve(p); // nouveau clic = vérification, jamais un 2e appel
67
+ }
68
+ return send(res, 202, { status: p.status });
69
+ }
70
+
71
+ if (req.method === 'POST' && path === '/webhook') {
72
+ const raw = await read(req);
73
+ const expected = crypto.createHmac('sha256', SECRET).update(raw).digest();
74
+ const got = Buffer.from(String(req.headers['x-signature'] || ''), 'hex');
75
+ if (got.length !== expected.length || !crypto.timingSafeEqual(got, expected)) return send(res, 401, {}); // règle 4
76
+ const b = JSON.parse(raw);
77
+ const p = payments.get(b.external_reference) || [...payments.values()].find(x => x.reference === b.reference);
78
+ if (p) { if (!p.reference) p.reference = b.reference; await resolve(p); } // relire chez le fournisseur
79
+ return send(res, 200, {});
80
+ }
81
+
82
+ if (req.method === 'POST' && path === '/_test/reconcile') { // job de rapprochement (règle 5)
83
+ await Promise.all([...payments.values()].filter(p => OPEN.includes(p.status) || p.status === 'EXPIRED').map(resolve));
84
+ return send(res, 200, {});
85
+ }
86
+
87
+ if (req.method === 'POST' && path === '/_test/force-expiry') { // expiration : lire d'abord (faille 3)
88
+ for (const p of [...payments.values()].filter(x => OPEN.includes(x.status))) {
89
+ await resolve(p);
90
+ transition(p, OPEN, 'EXPIRED');
91
+ }
92
+ return send(res, 200, {});
93
+ }
94
+
95
+ if (req.method === 'GET' && path.startsWith('/orders/')) {
96
+ const p = payments.get(byOrder.get(decodeURIComponent(path.split('/').pop())));
97
+ return send(res, 200, { status: p ? p.status : 'INCONNU' });
98
+ }
99
+ if (req.method === 'GET' && path.startsWith('/_test/effects/')) return send(res, 200, { count: effects.get(decodeURIComponent(path.split('/').pop())) || 0 });
100
+ send(res, 404, {});
101
+ }).listen(PORT, () => console.log(`Marchand robuste sur ${SELF}`));
@@ -0,0 +1,20 @@
1
+ # Rapport de crash-test mobile money
2
+
3
+ Dialecte : campay — 2026-11-27
4
+
5
+ **1/10 scénarios réussis.** Perte simulée sur 10 commandes de 5 000 FCFA : **134 950 FCFA**.
6
+
7
+ | Résultat | Scénario | Ce qui s'est passé | Risque si ça échoue |
8
+ |---|---|---|---|
9
+ | **échec** | Double clic simultané sur « Payer » | 2 débit(s), commande PAID | client débité deux fois |
10
+ | **échec** | Réponse de l'opérateur perdue, le client réessaie | 2 débit(s), commande PAID | double débit après coupure réseau |
11
+ | **échec** | Notification de paiement jamais reçue | opérateur : réussi, commande EXPIRED | client débité sans être servi |
12
+ | **échec** | Même notification reçue 20 fois en même temps | 20 livraison(s), commande PAID | livraison ou crédit en double |
13
+ | **échec** | Fausse notification « réussi » (signature invalide) | opérateur : en attente, commande PAID | livraison sans paiement |
14
+ | **échec** | Notification signée « réussi » alors que l'opérateur dit « en attente » | opérateur : en attente, commande PAID | livraison sans paiement (rejeu, fuite de clé) |
15
+ | **échec** | Le montant réellement payé est de 50 FCFA au lieu de 5 000 | commande PAID | produit livré pour presque rien |
16
+ | **échec** | Notification « échoué » reçue après un succès | opérateur : réussi, commande FAILED | commande payée annulée par erreur |
17
+ | réussi | Le client valide après l'expiration côté appli | opérateur : réussi, commande PAID | client débité, commande expirée en silence |
18
+ | **échec** | Jeton d'accès expiré pendant l'activité | 0 débit(s), commande INCONNU | paiements impossibles jusqu'au redémarrage |
19
+
20
+ Corrections : voir `references/core/concurrence-et-incertitude.md` et `references/core/idempotence.md`.
@@ -0,0 +1,20 @@
1
+ # Rapport de crash-test mobile money
2
+
3
+ Dialecte : campay — 2026-11-27
4
+
5
+ **10/10 scénarios réussis.** Perte simulée sur 10 commandes de 5 000 FCFA : **0 FCFA**.
6
+
7
+ | Résultat | Scénario | Ce qui s'est passé | Risque si ça échoue |
8
+ |---|---|---|---|
9
+ | réussi | Double clic simultané sur « Payer » | 1 débit(s), commande PAID | client débité deux fois |
10
+ | réussi | Réponse de l'opérateur perdue, le client réessaie | 1 débit(s), commande PAID | double débit après coupure réseau |
11
+ | réussi | Notification de paiement jamais reçue | opérateur : réussi, commande PAID | client débité sans être servi |
12
+ | réussi | Même notification reçue 20 fois en même temps | 1 livraison(s), commande PAID | livraison ou crédit en double |
13
+ | réussi | Fausse notification « réussi » (signature invalide) | opérateur : en attente, commande PENDING | livraison sans paiement |
14
+ | réussi | Notification signée « réussi » alors que l'opérateur dit « en attente » | opérateur : en attente, commande PENDING | livraison sans paiement (rejeu, fuite de clé) |
15
+ | réussi | Le montant réellement payé est de 50 FCFA au lieu de 5 000 | commande NEEDS_REVIEW | produit livré pour presque rien |
16
+ | réussi | Notification « échoué » reçue après un succès | opérateur : réussi, commande PAID | commande payée annulée par erreur |
17
+ | réussi | Le client valide après l'expiration côté appli | opérateur : réussi, commande NEEDS_REVIEW | client débité, commande expirée en silence |
18
+ | réussi | Jeton d'accès expiré pendant l'activité | 1 débit(s), commande PAID | paiements impossibles jusqu'au redémarrage |
19
+
20
+ Aucune faille détectée sur ces scénarios.
@@ -0,0 +1,20 @@
1
+ # Rapport de crash-test mobile money
2
+
3
+ Dialecte : generic — 2026-11-27
4
+
5
+ **1/9 scénarios réussis.** Perte simulée sur 9 commandes de 5 000 FCFA : **129 950 FCFA**.
6
+
7
+ | Résultat | Scénario | Ce qui s'est passé | Risque si ça échoue |
8
+ |---|---|---|---|
9
+ | **échec** | Double clic simultané sur « Payer » | 2 débit(s), commande PAID | client débité deux fois |
10
+ | **échec** | Réponse de l'opérateur perdue, le client réessaie | 2 débit(s), commande PAID | double débit après coupure réseau |
11
+ | **échec** | Notification de paiement jamais reçue | opérateur : réussi, commande EXPIRED | client débité sans être servi |
12
+ | **échec** | Même notification reçue 20 fois en même temps | 20 livraison(s), commande PAID | livraison ou crédit en double |
13
+ | **échec** | Fausse notification « réussi » (signature invalide) | opérateur : en attente, commande PAID | livraison sans paiement |
14
+ | **échec** | Notification signée « réussi » alors que l'opérateur dit « en attente » | opérateur : en attente, commande PAID | livraison sans paiement (rejeu, fuite de clé) |
15
+ | **échec** | Le montant réellement payé est de 50 FCFA au lieu de 5 000 | commande PAID | produit livré pour presque rien |
16
+ | **échec** | Notification « échoué » reçue après un succès | opérateur : réussi, commande FAILED | commande payée annulée par erreur |
17
+ | non testé | Jeton d'accès expiré pendant l'activité | sans objet pour ce dialecte | paiements impossibles jusqu'au redémarrage |
18
+ | réussi | Le client valide après l'expiration côté appli | opérateur : réussi, commande PAID | client débité, commande expirée en silence |
19
+
20
+ Corrections : voir `references/core/concurrence-et-incertitude.md` et `references/core/idempotence.md`.
@@ -0,0 +1,20 @@
1
+ # Rapport de crash-test mobile money
2
+
3
+ Dialecte : generic — 2026-11-27
4
+
5
+ **9/9 scénarios réussis.** Perte simulée sur 9 commandes de 5 000 FCFA : **0 FCFA**.
6
+
7
+ | Résultat | Scénario | Ce qui s'est passé | Risque si ça échoue |
8
+ |---|---|---|---|
9
+ | réussi | Double clic simultané sur « Payer » | 1 débit(s), commande PAID | client débité deux fois |
10
+ | réussi | Réponse de l'opérateur perdue, le client réessaie | 1 débit(s), commande PAID | double débit après coupure réseau |
11
+ | réussi | Notification de paiement jamais reçue | opérateur : réussi, commande PAID | client débité sans être servi |
12
+ | réussi | Même notification reçue 20 fois en même temps | 1 livraison(s), commande PAID | livraison ou crédit en double |
13
+ | réussi | Fausse notification « réussi » (signature invalide) | opérateur : en attente, commande PENDING | livraison sans paiement |
14
+ | réussi | Notification signée « réussi » alors que l'opérateur dit « en attente » | opérateur : en attente, commande PENDING | livraison sans paiement (rejeu, fuite de clé) |
15
+ | réussi | Le montant réellement payé est de 50 FCFA au lieu de 5 000 | commande NEEDS_REVIEW | produit livré pour presque rien |
16
+ | réussi | Notification « échoué » reçue après un succès | opérateur : réussi, commande PAID | commande payée annulée par erreur |
17
+ | réussi | Le client valide après l'expiration côté appli | opérateur : réussi, commande NEEDS_REVIEW | client débité, commande expirée en silence |
18
+ | non testé | Jeton d'accès expiré pendant l'activité | sans objet pour ce dialecte | paiements impossibles jusqu'au redémarrage |
19
+
20
+ Aucune faille détectée sur ces scénarios.
@@ -0,0 +1,160 @@
1
+ // Faux fournisseur mobile money qui reproduit les pannes réelles. Node 18+, aucune dépendance.
2
+ // Deux dialectes :
3
+ // generic : API simple (/v1/collect, /v1/transactions/...), notification POST signée HMAC-SHA256
4
+ // campay : imite l'API CamPay (/api/token/, /api/collect/, /api/transaction/{ref}/), notification GET signée JWT HS256
5
+ // API de pilotage (lanceur de scénarios uniquement) : /_admin/* — identique pour tous les dialectes.
6
+ import http from 'node:http';
7
+ import crypto from 'node:crypto';
8
+
9
+ const b64u = b => Buffer.from(b).toString('base64url');
10
+ export function signJwtHS256(payload, key) {
11
+ const head = b64u(JSON.stringify({ alg: 'HS256', typ: 'JWT' })), body = b64u(JSON.stringify(payload));
12
+ return `${head}.${body}.${crypto.createHmac('sha256', key).update(`${head}.${body}`).digest('base64url')}`;
13
+ }
14
+
15
+ export function startSimulator(opts = {}) {
16
+ const { port = 4010, dialect = 'generic', secret = 'whsec_test', apiKey = 'test_key',
17
+ username = 'app_user', password = 'app_pass', webhookKey = 'campay_webhook_key', webhookUrl = null,
18
+ tokenTtlSec = 3600, dedupeExternalReference = dialect === 'generic' } = opts;
19
+
20
+ const tx = new Map(), byExt = new Map(), plans = new Map(), queries = new Map(), tokens = new Map();
21
+ const view = t => ({ reference: t.reference, external_reference: t.external_reference, amount: t.reportedAmount ?? t.amount,
22
+ currency: t.currency, phone: t.phone, status: t.status });
23
+ const campayView = t => ({ reference: t.reference, external_reference: t.external_reference, status: t.status,
24
+ amount: t.reportedAmount ?? t.amount, currency: t.currency, operator: t.operator, code: t.code,
25
+ operator_reference: t.status === 'SUCCESSFUL' ? t.operatorRef : null, description: t.description });
26
+ const operatorOf = phone => /^2376(9|5[5-9])/.test(phone) ? 'ORANGE' : 'MTN';
27
+
28
+ async function deliver(t, { status, amount, forge = false } = {}) {
29
+ try {
30
+ if (dialect === 'campay') {
31
+ const target = webhookUrl || t.callback_url; if (!target) return;
32
+ const v = { ...campayView(t), ...(status ? { status } : {}), ...(amount ? { amount } : {}) };
33
+ const sig = signJwtHS256({ iat: Math.floor(Date.now() / 1000) }, forge ? 'mauvaise_cle' : webhookKey);
34
+ const qs = new URLSearchParams(Object.entries({ ...v, signature: sig }).filter(([, x]) => x != null).map(([k, x]) => [k, String(x)]));
35
+ await fetch(`${target}${target.includes('?') ? '&' : '?'}${qs}`, { method: 'GET' });
36
+ } else {
37
+ if (!t.callback_url) return;
38
+ const body = JSON.stringify({ event: 'transaction.updated', ...view(t), ...(status ? { status } : {}), ...(amount ? { amount } : {}) });
39
+ const sig = forge ? 'f'.repeat(64) : crypto.createHmac('sha256', secret).update(body).digest('hex');
40
+ await fetch(t.callback_url, { method: 'POST', headers: { 'content-type': 'application/json', 'x-signature': sig }, body });
41
+ }
42
+ } catch { }
43
+ }
44
+
45
+ function settleLater(t) {
46
+ const p = t.plan;
47
+ if (p.manual) return;
48
+ setTimeout(() => {
49
+ t.status = p.outcome || 'SUCCESSFUL';
50
+ if (p.webhook === 'none') return;
51
+ setTimeout(() => deliver(t), p.webhookDelayMs || 0);
52
+ }, p.approveAfterMs ?? 150);
53
+ }
54
+
55
+ function create({ amount, currency, phone, external_reference, callback_url, description }) {
56
+ const plan = plans.get(phone) || {};
57
+ const t = { reference: (dialect === 'campay' ? '' : 'sim_') + crypto.randomUUID(), external_reference: external_reference || null,
58
+ amount, currency: currency || 'XAF', phone, callback_url, description, status: 'PENDING', plan, reportedAmount: plan.reportedAmount,
59
+ operator: operatorOf(phone), code: 'CP' + Date.now().toString().slice(-10), operatorRef: String(Math.floor(1e9 + Math.random() * 9e9)) };
60
+ tx.set(t.reference, t);
61
+ if (t.external_reference && !byExt.has(t.external_reference)) byExt.set(t.external_reference, t.reference);
62
+ settleLater(t);
63
+ return t;
64
+ }
65
+
66
+ const readRaw = req => new Promise(r => { let b = ''; req.on('data', c => b += c); req.on('end', () => r(b)); });
67
+ const read = async req => { try { return JSON.parse((await readRaw(req)) || '{}'); } catch { return null; } };
68
+ const send = (res, code, obj) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(obj)); };
69
+ const countQuery = t => queries.set(t.reference, (queries.get(t.reference) || 0) + 1);
70
+
71
+ async function generic(req, res, url, path) {
72
+ if (req.headers['x-api-key'] !== apiKey) return send(res, 401, { error: 'INVALID_API_KEY' });
73
+ if (req.method === 'POST' && path === '/v1/collect') {
74
+ const b = await read(req);
75
+ if (!b || !Number.isSafeInteger(b.amount) || b.amount <= 0) return send(res, 400, { error: 'INVALID_AMOUNT' });
76
+ if (!/^2376\d{8}$/.test(String(b.phone))) return send(res, 400, { error: 'INVALID_PHONE' });
77
+ if (dedupeExternalReference && b.external_reference && byExt.has(b.external_reference))
78
+ return send(res, 409, { error: 'DUPLICATE_REFERENCE', reference: byExt.get(b.external_reference) });
79
+ const t = create(b);
80
+ if (t.plan.dropResponses > 0) { t.plan.dropResponses--; return req.socket.destroy(); }
81
+ return send(res, 202, view(t));
82
+ }
83
+ if (req.method === 'GET' && path === '/v1/transactions') {
84
+ const ref = byExt.get(url.searchParams.get('external_reference'));
85
+ return ref ? send(res, 200, view(tx.get(ref))) : send(res, 404, { error: 'NOT_FOUND' });
86
+ }
87
+ if (req.method === 'GET' && path.startsWith('/v1/transactions/')) {
88
+ const t = tx.get(path.split('/').pop()); if (!t) return send(res, 404, { error: 'NOT_FOUND' });
89
+ countQuery(t); return send(res, 200, view(t));
90
+ }
91
+ send(res, 404, { error: 'NOT_FOUND' });
92
+ }
93
+
94
+ async function campay(req, res, url, path) {
95
+ if (req.method === 'POST' && path === '/api/token/') {
96
+ const b = await read(req);
97
+ if (!b || b.username !== username || b.password !== password) return send(res, 400, { message: 'Invalid credentials' });
98
+ const token = crypto.randomBytes(20).toString('hex');
99
+ tokens.set(token, Date.now() + tokenTtlSec * 1000);
100
+ return send(res, 200, { token, expires_in: tokenTtlSec });
101
+ }
102
+ const m = /^Token (\S+)$/.exec(req.headers.authorization || '');
103
+ if (!m || !tokens.has(m[1]) || tokens.get(m[1]) < Date.now()) return send(res, 401, { detail: 'Invalid or expired token.' });
104
+
105
+ if (req.method === 'POST' && path === '/api/collect/') {
106
+ const b = await read(req);
107
+ const amount = Number(b?.amount);
108
+ if (!b || !/^\d+$/.test(String(b.amount)) || amount <= 0) return send(res, 400, { message: 'Invalid amount', error_code: 'ER201' });
109
+ if (!/^2376\d{8}$/.test(String(b.from))) return send(res, 400, { message: 'Invalid phone number. Ensure the number starts with the country code. e.g 237xxxxxxxxx', error_code: 'ER101' });
110
+ if (dedupeExternalReference && b.external_reference && byExt.has(b.external_reference))
111
+ return send(res, 400, { message: 'Duplicate external reference', error_code: 'ER_DUPLICATE' });
112
+ const t = create({ amount, currency: b.currency, phone: String(b.from), external_reference: b.external_reference, description: b.description });
113
+ if (t.plan.dropResponses > 0) { t.plan.dropResponses--; return req.socket.destroy(); }
114
+ return send(res, 200, { reference: t.reference, ussd_code: t.operator === 'MTN' ? '*126#' : '#150*50#', operator: t.operator });
115
+ }
116
+ if (req.method === 'GET' && path.startsWith('/api/transaction/')) {
117
+ const t = tx.get(path.split('/').filter(Boolean).pop()); if (!t) return send(res, 404, { message: 'Not found' });
118
+ countQuery(t); return send(res, 200, campayView(t));
119
+ }
120
+ if (req.method === 'POST' && path === '/api/history/') { // forme supposée, voir README (à confirmer)
121
+ return send(res, 200, { data: [...tx.values()].map(campayView) });
122
+ }
123
+ send(res, 404, { message: 'Not found' });
124
+ }
125
+
126
+ const server = http.createServer(async (req, res) => {
127
+ const url = new URL(req.url, 'http://x'), path = url.pathname;
128
+
129
+ if (path.startsWith('/_admin/')) {
130
+ if (req.method === 'POST' && path === '/_admin/plan') { const b = await read(req); plans.set(b.phone, { ...b.plan }); return send(res, 200, {}); }
131
+ if (req.method === 'GET' && path.startsWith('/_admin/phone/')) {
132
+ const phone = path.split('/').pop(), list = [...tx.values()].filter(t => t.phone === phone);
133
+ return send(res, 200, { transactions: list.map(view), debits: list.filter(t => t.status === 'SUCCESSFUL').length,
134
+ queries: list.reduce((s, t) => s + (queries.get(t.reference) || 0), 0) });
135
+ }
136
+ if (req.method === 'POST' && path === '/_admin/settle') {
137
+ const b = await read(req), t = tx.get(b.reference); if (!t) return send(res, 404, {});
138
+ t.status = b.status; if (b.webhook !== false) await deliver(t); return send(res, 200, view(t));
139
+ }
140
+ if (req.method === 'POST' && path === '/_admin/webhook') {
141
+ const b = await read(req), t = tx.get(b.reference); if (!t) return send(res, 404, {});
142
+ const n = b.times || 1, o = { status: b.status, amount: b.amount, forge: !!b.forge };
143
+ if (b.concurrent) await Promise.all(Array.from({ length: n }, () => deliver(t, o)));
144
+ else for (let i = 0; i < n; i++) await deliver(t, o);
145
+ return send(res, 200, {});
146
+ }
147
+ if (req.method === 'POST' && path === '/_admin/expire-tokens') { tokens.clear(); return send(res, 200, {}); }
148
+ return send(res, 404, {});
149
+ }
150
+ return dialect === 'campay' ? campay(req, res, url, path) : generic(req, res, url, path);
151
+ });
152
+
153
+ return new Promise(resolve => server.listen(port, () => resolve({ server, close: () => new Promise(r => server.close(r)) })));
154
+ }
155
+
156
+ if (import.meta.url === `file://${process.argv[1]}`) {
157
+ const port = Number(process.env.PORT || 4010), dialect = process.env.DIALECT || 'generic';
158
+ await startSimulator({ port, dialect, webhookUrl: process.env.WEBHOOK_URL || null });
159
+ console.log(`Simulateur mobile money (${dialect}) sur http://localhost:${port}`);
160
+ }
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@leonelmaken/kinyan",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Vérifie qu'un paiement mobile money (CamPay, Notch Pay, GSMA) est vraiment arrivé avant de livrer. Zéro dépendance.",
5
+ "keywords": ["mobile-money", "campay", "notchpay", "gsma", "paiement", "cameroun", "cemac", "momo", "orange-money", "webhook", "idempotence"],
6
+ "type": "module",
7
+ "main": "src/index.mjs",
8
+ "exports": { ".": "./src/index.mjs" },
9
+ "bin": { "kinyan-crash-test": "crash-test/chaos.mjs" },
10
+ "files": ["src/", "crash-test/", "apps/verifie/server.mjs", "apps/verifie/index.html", "apps/verifie/.env.example", "README.md", "LICENSE"],
11
+ "scripts": { "test": "node --test test/core.test.mjs test/adapters.test.mjs test/verify.test.mjs" },
12
+ "repository": { "type": "git", "url": "git+https://github.com/leonelmaken/kinyan.git" },
13
+ "homepage": "https://github.com/leonelmaken/kinyan#readme",
14
+ "bugs": { "url": "https://github.com/leonelmaken/kinyan/issues" },
15
+ "publishConfig": { "access": "public" },
16
+ "engines": { "node": ">=18" },
17
+ "license": "MIT",
18
+ "author": "Leonel Maken <https://leonelmaken.com>"
19
+ }
20
+