@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.
- package/LICENSE +21 -0
- package/README.md +107 -2
- package/apps/verifie/.env.example +14 -0
- package/apps/verifie/index.html +92 -0
- package/apps/verifie/server.mjs +60 -0
- package/crash-test/README.md +90 -0
- package/crash-test/chaos.mjs +124 -0
- package/crash-test/exemples/badge-campay-naif.svg +1 -0
- package/crash-test/exemples/badge-campay-robuste.svg +1 -0
- package/crash-test/exemples/campay-naif.mjs +52 -0
- package/crash-test/exemples/campay-robuste.mjs +112 -0
- package/crash-test/exemples/chaos.campay-naif.json +13 -0
- package/crash-test/exemples/chaos.campay-robuste.json +13 -0
- package/crash-test/exemples/chaos.naif.json +13 -0
- package/crash-test/exemples/chaos.robuste.json +13 -0
- package/crash-test/exemples/github-action.yml +27 -0
- package/crash-test/exemples/marchand-naif.mjs +47 -0
- package/crash-test/exemples/marchand-robuste.mjs +101 -0
- package/crash-test/exemples/rapport-campay-naif.md +20 -0
- package/crash-test/exemples/rapport-campay-robuste.md +20 -0
- package/crash-test/exemples/rapport-naif.md +20 -0
- package/crash-test/exemples/rapport-robuste.md +20 -0
- package/crash-test/simulateur.mjs +160 -0
- package/package.json +18 -4
- package/src/adapters/campay.mjs +84 -0
- package/src/adapters/gsma.mjs +85 -0
- package/src/adapters/notchpay.mjs +78 -0
- package/src/index.mjs +8 -0
- package/src/ledger.mjs +63 -0
- package/src/mandate.mjs +42 -0
- package/src/money.mjs +75 -0
- package/src/payment.mjs +91 -0
- package/src/verify.mjs +96 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Leonel Maken
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,108 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Kinyan — le langage commun des paiements
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> En hébreu, *kinyan* (קִנְיָן) est le geste qui rend un échange définitif. Kinyan prouve qu'un paiement est vraiment arrivé avant que tu livres.
|
|
4
|
+
|
|
5
|
+
Kinyan est une bibliothèque open source (Node 18+, **zéro dépendance**) qui s'installe **dans ton appli**. Elle ne touche jamais l'argent, n'oriente aucun paiement et ne règle rien : tu gardes tes propres contrats et identifiants chez chaque fournisseur. Elle ne te met donc pas dans le flux de paiement, la position qui fait de toi un prestataire régulé (COBAC en zone CEMAC, et ailleurs).
|
|
6
|
+
|
|
7
|
+
## Vérifie avant de livrer (outil gratuit pour les commerçants)
|
|
8
|
+
|
|
9
|
+
Le client montre une capture « Paiement réussi » ou un SMS. **Ce n'est pas une preuve** : ça se fabrique en 30 secondes.
|
|
10
|
+
L'outil demande directement à TON compte (CamPay, Notch Pay…) si l'argent est arrivé, et répond en gros :
|
|
11
|
+
|
|
12
|
+
| Réponse | Quand |
|
|
13
|
+
|---|---|
|
|
14
|
+
| ✅ **Tu peux livrer** | l'argent est sur ton compte, au bon montant, et ce reçu n'a jamais servi |
|
|
15
|
+
| ⏳ **Attends** | le client n'a pas encore validé, ou le service ne répond pas |
|
|
16
|
+
| ⛔ **Ne livre pas** | référence inconnue, paiement échoué, montant trop petit, reçu trop vieux ou **déjà utilisé** |
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @leonelmaken/kinyan # dans ton projet
|
|
20
|
+
# ou, pour essayer l'outil tout de suite :
|
|
21
|
+
git clone https://github.com/leonelmaken/kinyan && cd kinyan
|
|
22
|
+
node apps/verifie/server.mjs # mode démo, sans compte ni clé
|
|
23
|
+
cp apps/verifie/.env.example apps/verifie/.env # puis remplis FOURNISSEUR et tes clés
|
|
24
|
+
node --env-file=apps/verifie/.env apps/verifie/server.mjs
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Dans ton code :
|
|
28
|
+
|
|
29
|
+
```js
|
|
30
|
+
import { createVerifier, notchpayProvider } from '@leonelmaken/kinyan';
|
|
31
|
+
const verifier = createVerifier({ provider: notchpayProvider({ publicKey: process.env.NOTCHPAY_PUBLIC_KEY }) });
|
|
32
|
+
const r = await verifier.check({ reference: 'MP261201.1530.A12345', expectedAmount: 5000 });
|
|
33
|
+
if (r.verdict === 'LIVRER') { /* donner la marchandise */ }
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Garanties : en cas de panne, jamais « livrer » ; un même reçu ne sert qu'une fois, même tapé autrement (`mp-12 34` = `MP1234`) ou à deux caisses en même temps.
|
|
37
|
+
Plusieurs serveurs : remplace `fileStore` par une table avec contrainte UNIQUE sur la référence.
|
|
38
|
+
|
|
39
|
+
**Testé en bac à sable (déc. 2026) :**
|
|
40
|
+
- **CamPay (demo.campay.net)** : la lecture `GET /api/transaction/{ref}/` fonctionne ; une référence inconnue (403 « Invalid transaction reference ») est traitée comme introuvable. ⚠️ Le bac à sable CamPay renvoie toujours un montant `0.00`, même pour un paiement réussi (CamPay : « le demo est juste pour les tests »). Kinyan refuse alors de dire « livrer » : c'est voulu (fail-closed). En compte Live, le vrai montant est renvoyé.
|
|
41
|
+
- **Notch Pay (clés `pk_test…`)** : la vérification se fait avec la référence Notch (`trx.test_…`), pas avec ta référence marchande.
|
|
42
|
+
- Pas encore confirmé : le comportement en compte **Live** sur un vrai paiement.
|
|
43
|
+
|
|
44
|
+
## Le problème (2026)
|
|
45
|
+
|
|
46
|
+
| Difficulté | Ce qui se passe | Ce que fait Kinyan |
|
|
47
|
+
|---|---|---|
|
|
48
|
+
| Fragmentation | 178 services de mobile money dans 54 pays, chacun avec son API | Un seul modèle de paiement, **aligné sur le standard GSMA Mobile Money API** ; un traducteur par fournisseur |
|
|
49
|
+
| Réponse perdue | Timeout : a-t-on débité le client ? On relance et on débite deux fois | Identifiant client créé avant l'appel (= `X-CorrelationID` GSMA), état `UNKNOWN`, récupération via `/responses/{id}` |
|
|
50
|
+
| Notifications | Perdues, en double, fausses, en retard | Signature vérifiée (refus si la clé manque), statut toujours relu, effet une seule fois, succès tardif → revue humaine |
|
|
51
|
+
| Règlement multi-devises | Payé en XAF, réglé net de frais en USD, en EUR ou en **USDC sous le mobile money** | Registre à **trois montants** (demandé, confirmé, réglé) et rapprochement automatique : écarts de change, frais, règlements manquants ou fantômes |
|
|
52
|
+
| Agents IA qui paient | Un agent IA utilise les identifiants d'un humain sans limite | **Mandats** : plafond par paiement et par jour, liste de bénéficiaires, validation humaine au-delà d'un seuil, clé d'idempotence obligatoire, piste d'audit |
|
|
53
|
+
| Nouveaux rails (GIMACPAY, PI-SPI…) | Encore un format à intégrer | Même modèle : un traducteur de plus, prouvé par le crash-test |
|
|
54
|
+
|
|
55
|
+
## Ce qu'il y a dedans
|
|
56
|
+
|
|
57
|
+
| Module | Rôle |
|
|
58
|
+
|---|---|
|
|
59
|
+
| `src/money.mjs` | Argent exact en entiers (XAF/XOF 0 décimale, USD/EUR 2, USDC/USDT 6), répartition exacte, conversion à arrondi explicite |
|
|
60
|
+
| `src/payment.mjs` | Modèle de paiement aligné GSMA, machine à états stricte, effet métier unique |
|
|
61
|
+
| `src/ledger.mjs` | Registre à trois montants, rapprochement, totaux par devise |
|
|
62
|
+
| `src/mandate.mjs` | Mandats de paiement pour agents IA |
|
|
63
|
+
| `src/adapters/gsma.mjs` | Traducteur pour **tout fournisseur conforme GSMA** |
|
|
64
|
+
| `src/adapters/campay.mjs` | Traducteur CamPay (Cameroun) |
|
|
65
|
+
| `src/adapters/notchpay.mjs` | Traducteur Notch Pay (signature `X-Notch-Signature` vérifiée) |
|
|
66
|
+
| `src/verify.mjs` | Vérificateur « livrer / attendre / ne pas livrer », registre anti-réutilisation des reçus |
|
|
67
|
+
| `apps/verifie/` | Petite page web prête à l'emploi pour le commerçant |
|
|
68
|
+
| `crash-test/` | Simulateur de pannes : 10 scénarios, perte chiffrée, badge, mode CI |
|
|
69
|
+
|
|
70
|
+
## En 20 lignes
|
|
71
|
+
|
|
72
|
+
```js
|
|
73
|
+
import { money, createPayment, gsmaProvider, reconcile, createMandate, authorize } from '@leonelmaken/kinyan';
|
|
74
|
+
|
|
75
|
+
const provider = gsmaProvider({ baseUrl: process.env.MMAPI_URL, headers: { Authorization: `Bearer ${process.env.MMAPI_TOKEN}` } });
|
|
76
|
+
|
|
77
|
+
const p = createPayment({ type: 'merchantpay', amount: money('5000', 'XAF'),
|
|
78
|
+
debitParty: [{ key: 'msisdn', value: '237677777777' }], creditParty: [{ key: 'walletid', value: 'BOUTIQUE' }] });
|
|
79
|
+
await db.save(p); // enregistrer AVANT l'appel : p.id est la clé anti-doublon
|
|
80
|
+
await provider.initiate(p); // PENDING, PAID, FAILED… ou UNKNOWN si le réseau a coupé
|
|
81
|
+
|
|
82
|
+
// Notification reçue, ou job de rapprochement : on relit toujours le statut chez le fournisseur.
|
|
83
|
+
const { effect } = await provider.refresh(p);
|
|
84
|
+
if (effect === 'FULFIL') await livrer(p); // garanti une seule fois
|
|
85
|
+
|
|
86
|
+
// Agent IA : il ne paie que dans son mandat.
|
|
87
|
+
const m = createMandate({ agentId: 'compta-ia', currency: 'XAF', maxPerPayment: '50000', maxPerDay: '100000',
|
|
88
|
+
humanApprovalAbove: '20000', allowedCounterparties: ['ENEO'], expiresAt: '2026-12-31', purpose: 'factures' });
|
|
89
|
+
authorize(m, { amount: money('30000', 'XAF'), counterparty: 'ENEO', type: 'billpay', idempotencyKey: 'f-12' }, { spentToday: money('0', 'XAF') });
|
|
90
|
+
// → { decision: 'NEEDS_HUMAN', reasons: ['au-dessus du seuil de validation humaine'] }
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Preuves
|
|
94
|
+
|
|
95
|
+
- `npm test` : 25 tests, dont un fournisseur GSMA simulé (réponse perdue puis nouvel essai = **1 seul débit**) et CamPay sur le crash-test (jeton expiré, réponse perdue, signature).
|
|
96
|
+
- `crash-test/` : intégration CamPay naïve **1/10, 134 950 FCFA perdus** ; intégration robuste **10/10, 0 FCFA**.
|
|
97
|
+
|
|
98
|
+
## Limites connues
|
|
99
|
+
|
|
100
|
+
- CamPay : le format de la signature des notifications, le refus des doublons de référence et la forme de l'historique ne sont pas documentés publiquement. Le traducteur prend l'hypothèse la plus prudente ; **à confirmer sur un compte démo**.
|
|
101
|
+
- GSMA : écrit d'après la spécification 1.2. Chaque fournisseur peut avoir des variantes (authentification, chemins) : `paths` et `headers` sont configurables.
|
|
102
|
+
- Kinyan ne donne aucun avis juridique et ne remplace ni l'agrément ni le KYC.
|
|
103
|
+
|
|
104
|
+
## Feuille de route
|
|
105
|
+
|
|
106
|
+
Test sur compte CamPay Live · traducteurs MTN MoMo, M-Pesa, Wave et PI-SPI (API Business) · dialecte GSMA du crash-test · import des relevés fournisseurs (CSV) dans le registre · skill pour assistants IA (issu de `fintech-cemac`).
|
|
107
|
+
|
|
108
|
+
Licence MIT — Leonel Maken
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Copie ce fichier en .env et remplis-le. Ne partage JAMAIS ton .env (ni dans un chat, ni sur GitHub).
|
|
2
|
+
FOURNISSEUR=demo # demo | campay | notchpay
|
|
3
|
+
CODE_BOUTIQUE= # code que les vendeurs tapent pour utiliser l'outil (conseillé)
|
|
4
|
+
AGE_MAX_HEURES=72 # un reçu plus vieux est refusé
|
|
5
|
+
PORT=4321
|
|
6
|
+
HOST=127.0.0.1 # 0.0.0.0 pour l'utiliser depuis les téléphones de la boutique (même Wi-Fi)
|
|
7
|
+
|
|
8
|
+
# Notch Pay (clé publique, test_… en bac à sable)
|
|
9
|
+
NOTCHPAY_PUBLIC_KEY=
|
|
10
|
+
|
|
11
|
+
# CamPay (identifiants de l'application, PAS ceux de ton compte)
|
|
12
|
+
CAMPAY_URL=https://demo.campay.net
|
|
13
|
+
CAMPAY_USERNAME=
|
|
14
|
+
CAMPAY_PASSWORD=
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="fr">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>Vérifie avant de livrer — Kinyan</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root { --bg:#f6f4ef; --ink:#1d1b17; --muted:#6b665c; --card:#fff; --line:#e4dfd4;
|
|
9
|
+
--ok:#1f8a4c; --ok-bg:#e3f5ea; --wait:#b7791f; --wait-bg:#fdf1dc; --no:#c0392b; --no-bg:#fbe6e3; }
|
|
10
|
+
* { box-sizing:border-box; }
|
|
11
|
+
body { margin:0; font:17px/1.45 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; background:var(--bg); color:var(--ink); }
|
|
12
|
+
main { max-width:460px; margin:0 auto; padding:20px 16px 40px; }
|
|
13
|
+
header { display:flex; align-items:baseline; justify-content:space-between; margin-bottom:6px; }
|
|
14
|
+
h1 { font-size:22px; margin:0; letter-spacing:-.01em; }
|
|
15
|
+
.mode { font-size:12px; color:var(--muted); border:1px solid var(--line); border-radius:99px; padding:2px 9px; }
|
|
16
|
+
p.lead { color:var(--muted); margin:4px 0 18px; }
|
|
17
|
+
form { background:var(--card); border:1px solid var(--line); border-radius:16px; padding:16px; display:grid; gap:12px; }
|
|
18
|
+
label { font-weight:600; font-size:15px; display:grid; gap:6px; }
|
|
19
|
+
input { font:inherit; font-size:20px; padding:12px 14px; border:1.5px solid var(--line); border-radius:12px; width:100%; background:#fff; }
|
|
20
|
+
input:focus { outline:none; border-color:var(--ink); }
|
|
21
|
+
button { font:inherit; font-weight:700; font-size:19px; padding:15px; border:0; border-radius:12px; background:var(--ink); color:#fff; cursor:pointer; }
|
|
22
|
+
button:disabled { opacity:.55; }
|
|
23
|
+
#res { margin-top:18px; border-radius:18px; padding:22px 18px; text-align:center; display:none; }
|
|
24
|
+
#res.show { display:block; animation:pop .35s cubic-bezier(.2,1.4,.4,1); }
|
|
25
|
+
#res .icon { font-size:62px; line-height:1; }
|
|
26
|
+
#res .big { font-size:28px; font-weight:800; margin:10px 0 6px; letter-spacing:.01em; }
|
|
27
|
+
#res .why { font-size:16px; }
|
|
28
|
+
.LIVRER { background:var(--ok-bg); color:var(--ok); }
|
|
29
|
+
.ATTENDRE { background:var(--wait-bg); color:var(--wait); }
|
|
30
|
+
.NE_PAS_LIVRER { background:var(--no-bg); color:var(--no); }
|
|
31
|
+
.NE_PAS_LIVRER .icon { animation:shake .5s; }
|
|
32
|
+
.ATTENDRE .icon { animation:spin 2s linear infinite; display:inline-block; }
|
|
33
|
+
.rule { margin-top:22px; font-size:14px; color:var(--muted); border-left:3px solid var(--line); padding-left:12px; }
|
|
34
|
+
.demo { margin-top:14px; font-size:14px; color:var(--muted); }
|
|
35
|
+
.demo code { background:#fff; border:1px solid var(--line); border-radius:6px; padding:1px 6px; cursor:pointer; }
|
|
36
|
+
@keyframes pop { from { transform:scale(.9); opacity:0 } to { transform:none; opacity:1 } }
|
|
37
|
+
@keyframes shake { 20%,60% { transform:translateX(-8px) } 40%,80% { transform:translateX(8px) } }
|
|
38
|
+
@keyframes spin { to { transform:rotate(360deg) } }
|
|
39
|
+
@media (prefers-reduced-motion: reduce) { * { animation:none !important } }
|
|
40
|
+
</style>
|
|
41
|
+
</head>
|
|
42
|
+
<body>
|
|
43
|
+
<main>
|
|
44
|
+
<header><h1>Vérifie avant de livrer</h1><span class="mode">mode __MODE__</span></header>
|
|
45
|
+
<p class="lead">Ne crois pas la capture d'écran. Demande à ton compte si l'argent est vraiment là.</p>
|
|
46
|
+
|
|
47
|
+
<form id="f" autocomplete="off">
|
|
48
|
+
<label>Référence du paiement
|
|
49
|
+
<input id="ref" required minlength="4" maxlength="80" placeholder="ex. MP261201.1530.A12345" autocapitalize="characters">
|
|
50
|
+
</label>
|
|
51
|
+
<label>Montant que tu attends (FCFA)
|
|
52
|
+
<input id="montant" required inputmode="numeric" pattern="[0-9 ]+" placeholder="5000">
|
|
53
|
+
</label>
|
|
54
|
+
<label id="codeWrap">Code boutique
|
|
55
|
+
<input id="code" type="password" inputmode="numeric" placeholder="laisse vide si aucun">
|
|
56
|
+
</label>
|
|
57
|
+
<button id="go">Vérifier</button>
|
|
58
|
+
</form>
|
|
59
|
+
|
|
60
|
+
<div id="res" role="status" aria-live="polite"><div class="icon"></div><div class="big"></div><div class="why"></div></div>
|
|
61
|
+
|
|
62
|
+
<p class="rule">Règle simple : pas de confirmation ici = pas de marchandise. Même si le client insiste, même s'il montre un SMS.</p>
|
|
63
|
+
<p class="demo" id="demo" hidden>Essai : touche <code>DEMO-OK-5000</code> <code>DEMO-ATTENTE</code> <code>DEMO-ECHEC</code> <code>DEMO-VIEUX</code> ou invente une référence.</p>
|
|
64
|
+
</main>
|
|
65
|
+
<script>
|
|
66
|
+
const $ = id => document.getElementById(id);
|
|
67
|
+
const LOOK = { LIVRER: ['✅', 'Tu peux livrer'], ATTENDRE: ['⏳', 'Attends'], NE_PAS_LIVRER: ['⛔', 'Ne livre pas'] };
|
|
68
|
+
if ('__MODE__' === 'demo') { $('demo').hidden = false; $('montant').value = '5000'; }
|
|
69
|
+
$('demo').addEventListener('click', e => { if (e.target.tagName === 'CODE') { $('ref').value = e.target.textContent; $('f').requestSubmit(); } });
|
|
70
|
+
try { $('code').value = sessionStorage.getItem('kinyan-code') || ''; } catch {}
|
|
71
|
+
|
|
72
|
+
$('f').addEventListener('submit', async e => {
|
|
73
|
+
e.preventDefault();
|
|
74
|
+
const res = $('res'); res.className = ''; $('go').disabled = true; $('go').textContent = 'Je demande à ton compte…';
|
|
75
|
+
let r;
|
|
76
|
+
try {
|
|
77
|
+
try { sessionStorage.setItem('kinyan-code', $('code').value); } catch {}
|
|
78
|
+
const http = await fetch('/api/verifier', { method: 'POST', headers: { 'content-type': 'application/json' },
|
|
79
|
+
body: JSON.stringify({ reference: $('ref').value, montant: $('montant').value.replace(/\s/g, ''), code: $('code').value }) });
|
|
80
|
+
r = await http.json();
|
|
81
|
+
} catch { r = { verdict: 'ATTENDRE', raison: "Pas de connexion avec l'outil. Ne livre pas encore." }; }
|
|
82
|
+
const [icon, big] = LOOK[r.verdict] || LOOK.NE_PAS_LIVRER;
|
|
83
|
+
res.querySelector('.icon').textContent = icon;
|
|
84
|
+
res.querySelector('.big').textContent = big;
|
|
85
|
+
res.querySelector('.why').textContent = r.raison || '';
|
|
86
|
+
void res.offsetWidth; res.className = 'show ' + (LOOK[r.verdict] ? r.verdict : 'NE_PAS_LIVRER');
|
|
87
|
+
if (navigator.vibrate && r.verdict === 'NE_PAS_LIVRER') navigator.vibrate([120, 60, 120]);
|
|
88
|
+
$('go').disabled = false; $('go').textContent = 'Vérifier';
|
|
89
|
+
});
|
|
90
|
+
</script>
|
|
91
|
+
</body>
|
|
92
|
+
</html>
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// « Vérifie avant de livrer » — petit serveur sans dépendance.
|
|
3
|
+
// Lancer : node --env-file=.env apps/verifie/server.mjs (ou sans .env : mode démo)
|
|
4
|
+
// Les clés restent dans TON .env, sur TA machine. Elles ne partent jamais vers le navigateur.
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { createVerifier, fileStore, demoProvider, campayProvider, notchpayProvider } from '../../src/index.mjs';
|
|
11
|
+
|
|
12
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
// Une valeur du .env peut porter un commentaire en fin de ligne : « demo # ... » -> « demo ».
|
|
14
|
+
const env = Object.fromEntries(Object.entries(process.env).map(([k, v]) => [k, String(v).replace(/\s+#.*$/, '').trim()]));
|
|
15
|
+
const PROVIDER = (env.FOURNISSEUR || 'demo').toLowerCase();
|
|
16
|
+
|
|
17
|
+
function makeProvider() {
|
|
18
|
+
if (PROVIDER === 'notchpay') return notchpayProvider({ publicKey: env.NOTCHPAY_PUBLIC_KEY });
|
|
19
|
+
if (PROVIDER === 'campay') return campayProvider({ baseUrl: env.CAMPAY_URL || 'https://demo.campay.net',
|
|
20
|
+
username: env.CAMPAY_USERNAME, password: env.CAMPAY_PASSWORD });
|
|
21
|
+
if (PROVIDER === 'demo') return demoProvider();
|
|
22
|
+
throw new Error(`FOURNISSEUR inconnu : ${PROVIDER} (demo, campay ou notchpay)`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
fs.mkdirSync(path.join(here, 'data'), { recursive: true });
|
|
26
|
+
const verifier = createVerifier({ provider: makeProvider(),
|
|
27
|
+
store: fileStore(path.join(here, 'data', `references-utilisees-${PROVIDER}.json`)),
|
|
28
|
+
maxAgeHours: Number(env.AGE_MAX_HEURES || 72) });
|
|
29
|
+
|
|
30
|
+
const page = fs.readFileSync(path.join(here, 'index.html'), 'utf8').replaceAll('__MODE__', PROVIDER);
|
|
31
|
+
const CODE = env.CODE_BOUTIQUE || '';
|
|
32
|
+
const sameCode = c => { const a = Buffer.from(String(c || '')), b = Buffer.from(CODE); return a.length === b.length && crypto.timingSafeEqual(a, b); };
|
|
33
|
+
|
|
34
|
+
// Anti-devinette : 30 vérifications par minute et par appareil.
|
|
35
|
+
const hits = new Map();
|
|
36
|
+
const tooMany = ip => { const t = Date.now(), list = (hits.get(ip) || []).filter(x => t - x < 60_000); list.push(t); hits.set(ip, list); return list.length > 30; };
|
|
37
|
+
|
|
38
|
+
const send = (res, code, body, type = 'application/json; charset=utf-8') => {
|
|
39
|
+
res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
|
|
40
|
+
'content-security-policy': "default-src 'self'; style-src 'unsafe-inline'; script-src 'unsafe-inline'" });
|
|
41
|
+
res.end(typeof body === 'string' ? body : JSON.stringify(body));
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
http.createServer(async (req, res) => {
|
|
45
|
+
if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) return send(res, 200, page, 'text/html; charset=utf-8');
|
|
46
|
+
if (req.method === 'POST' && req.url === '/api/verifier') {
|
|
47
|
+
if (tooMany(req.socket.remoteAddress)) return send(res, 429, { verdict: 'ATTENDRE', raison: 'Trop de vérifications. Patiente une minute.' });
|
|
48
|
+
let raw = ''; for await (const c of req) { raw += c; if (raw.length > 4096) return send(res, 413, {}); }
|
|
49
|
+
let b; try { b = JSON.parse(raw); } catch { return send(res, 400, { verdict: 'NE_PAS_LIVRER', raison: 'Demande illisible.' }); }
|
|
50
|
+
if (CODE && !sameCode(b.code)) return send(res, 401, { verdict: 'NE_PAS_LIVRER', raison: 'Code boutique incorrect.' });
|
|
51
|
+
const r = await verifier.check({ reference: b.reference, expectedAmount: b.montant, cashier: String(b.caisse || '').slice(0, 40) || null });
|
|
52
|
+
console.log(new Date().toISOString(), r.verdict, String(b.reference).slice(0, 40));
|
|
53
|
+
return send(res, 200, r);
|
|
54
|
+
}
|
|
55
|
+
send(res, 404, { erreur: 'introuvable' });
|
|
56
|
+
}).listen(Number(env.PORT || 4321), env.HOST || '127.0.0.1', function () {
|
|
57
|
+
const a = this.address();
|
|
58
|
+
console.log(`Vérifie avant de livrer — mode ${PROVIDER} — http://${a.address}:${a.port}`);
|
|
59
|
+
if (PROVIDER === 'demo') console.log('Essaie : DEMO-OK-5000 (5000 F), DEMO-ATTENTE, DEMO-ECHEC, DEMO-VIEUX, ou une référence inventée.');
|
|
60
|
+
});
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Crash-test mobile money
|
|
2
|
+
|
|
3
|
+
Un faux fournisseur mobile money qui reproduit ce qui casse dans la vraie vie, et 10 scénarios qui attaquent ton appli. Résultat : un verdict par scénario, la perte simulée en FCFA, un badge et un code de sortie pour la CI. Node 18+, aucune dépendance.
|
|
4
|
+
|
|
5
|
+
**Dialecte CamPay** : le simulateur imite l'API CamPay. Une appli intégrée à CamPay se teste **sans modifier son code**, en changeant seulement l'adresse de l'API et les identifiants en mode test.
|
|
6
|
+
|
|
7
|
+
Pourquoi : les assistants IA (et les humains) écrivent du code de paiement qui marche en démo et casse sous la concurrence ou les pannes réseau. Relire le code ne suffit pas à voir ces failles. Les provoquer, si.
|
|
8
|
+
|
|
9
|
+
## Résultats sur les applis d'exemple
|
|
10
|
+
|
|
11
|
+
| Appli | Score | Perte simulée |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| Intégration CamPay naïve (`exemples/campay-naif.mjs`) | 1/10 | 134 950 FCFA |
|
|
14
|
+
| Intégration CamPay robuste (`exemples/campay-robuste.mjs`) | **10/10** | 0 FCFA |
|
|
15
|
+
| Appli générique naïve | 1/9 | 129 950 FCFA |
|
|
16
|
+
| Appli générique robuste | **9/9** | 0 FCFA |
|
|
17
|
+
|
|
18
|
+
L'intégration naïve reproduit des erreurs réellement rencontrées : notification crue sans vérifier la signature, pas de référence externe, jeton jamais renouvelé, « en attente = échec ».
|
|
19
|
+
|
|
20
|
+
## Essayer en 30 secondes
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
cd tools/chaos
|
|
24
|
+
PORT=4020 node exemples/marchand-naif.mjs & # appli volontairement mal écrite
|
|
25
|
+
PORT=4021 node exemples/marchand-robuste.mjs & # appli qui applique les 7 règles
|
|
26
|
+
node chaos.mjs exemples/chaos.naif.json # → 1/9, 129 950 FCFA perdus
|
|
27
|
+
node chaos.mjs exemples/chaos.robuste.json # → 9/9, 0 FCFA
|
|
28
|
+
|
|
29
|
+
# Dialecte CamPay
|
|
30
|
+
PORT=4030 node exemples/campay-naif.mjs &
|
|
31
|
+
PORT=4031 node exemples/campay-robuste.mjs &
|
|
32
|
+
node chaos.mjs exemples/chaos.campay-naif.json # → 1/10
|
|
33
|
+
node chaos.mjs exemples/chaos.campay-robuste.json # → 10/10 + badge
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Les 9 scénarios
|
|
37
|
+
|
|
38
|
+
| Scénario | Ce qui est simulé |
|
|
39
|
+
|---|---|
|
|
40
|
+
| Double clic | Deux demandes de paiement simultanées pour la même commande |
|
|
41
|
+
| Réponse perdue | L'opérateur reçoit la demande mais la réponse se perd ; le client réessaie |
|
|
42
|
+
| Notification perdue | Le paiement réussit, la notification n'arrive jamais |
|
|
43
|
+
| Notification ×20 | La même notification arrive 20 fois en même temps |
|
|
44
|
+
| Fausse signature | Un tiers envoie « réussi » avec une signature invalide |
|
|
45
|
+
| Notification menteuse | Message signé « réussi » alors que l'opérateur dit « en attente » |
|
|
46
|
+
| Montant différent | 50 FCFA payés au lieu de 5 000 |
|
|
47
|
+
| Échec après succès | Une notification « échoué » arrive après un succès |
|
|
48
|
+
| Succès tardif | Le client valide après l'expiration côté appli |
|
|
49
|
+
| Jeton expiré (CamPay) | Le jeton d'accès expire pendant que l'appli tourne |
|
|
50
|
+
|
|
51
|
+
Hypothèse : dans les scénarios de double débit, le client valide chaque demande reçue sur son téléphone.
|
|
52
|
+
|
|
53
|
+
## Brancher une appli CamPay existante (sans changer son code)
|
|
54
|
+
|
|
55
|
+
1. En mode test, configure ton appli avec : URL CamPay = `http://localhost:4010`, utilisateur `app_user`, mot de passe `app_pass`, clé webhook `campay_webhook_key`.
|
|
56
|
+
2. Copie `exemples/chaos.campay-robuste.json` et indique l'URL de ton webhook (`provider.webhookUrl`) et tes routes de test (ci-dessous).
|
|
57
|
+
3. `node chaos.mjs ton-fichier.json` → rapport + badge `crash-test paiements 10/10` à mettre dans ton README.
|
|
58
|
+
4. En CI : `exemples/github-action.yml` bloque une pull request qui casse les paiements.
|
|
59
|
+
|
|
60
|
+
Ce que le dialecte CamPay imite (vérifié sur des SDK publics, novembre 2026) : `POST /api/token/` → `{ token, expires_in }` ; en-tête `Authorization: Token <jeton>` ; `POST /api/collect/` avec `amount` (texte), `currency`, `from` (`2376XXXXXXXX`), `description`, `external_reference` → `{ reference, ussd_code, operator }` ; `GET /api/transaction/{reference}/` → `reference, external_reference, status, amount, currency, operator, code, operator_reference` ; statuts `PENDING`, `SUCCESSFUL`, `FAILED` ; erreur `ER101` pour un numéro invalide ; notification par `GET` sur l'URL configurée, avec les mêmes champs et un paramètre `signature`.
|
|
61
|
+
|
|
62
|
+
**À confirmer sur la documentation officielle CamPay** (simulé ici avec l'hypothèse la plus prudente) : la signature est un JWT HS256 signé avec la clé webhook de l'application ; CamPay ne refuse pas une `external_reference` déjà utilisée (le simulateur l'accepte, donc ton appli doit se protéger seule) ; la forme exacte de l'historique des transactions (`POST /api/history/`).
|
|
63
|
+
|
|
64
|
+
## Brancher une autre appli (format générique)
|
|
65
|
+
|
|
66
|
+
1. **En mode test, fais pointer ton adaptateur de paiement vers le simulateur** (`http://localhost:4010`). C'est simple si ton code passe par une interface `PaymentProvider` : ajoute une implémentation `ChaosProvider` qui parle l'API du simulateur (ci-dessous).
|
|
67
|
+
2. **Expose 2 à 4 routes de test** (désactivées en production) :
|
|
68
|
+
- `GET /orders/{orderId}` → `{ "status": "..." }` (obligatoire)
|
|
69
|
+
- `POST` qui lance ton job de rapprochement (recommandé)
|
|
70
|
+
- `POST` qui lance ton job d'expiration (optionnel)
|
|
71
|
+
- `GET` qui renvoie `{ "count": n }`, le nombre de livraisons ou crédits déclenchés pour la commande (recommandé, seul moyen de voir un double effet)
|
|
72
|
+
3. Copie `exemples/chaos.robuste.json`, remplace les URL, lance `node chaos.mjs ton-fichier.json`. Code de sortie 1 en cas d'échec : utilisable en CI.
|
|
73
|
+
|
|
74
|
+
## API du simulateur
|
|
75
|
+
|
|
76
|
+
| Requête | Réponse |
|
|
77
|
+
|---|---|
|
|
78
|
+
| `POST /v1/collect` en-tête `x-api-key`, corps `{ amount, currency, phone, external_reference, callback_url }` | `202 { reference, status: "PENDING", ... }` ; `409 DUPLICATE_REFERENCE` si `external_reference` déjà vu |
|
|
79
|
+
| `GET /v1/transactions/{reference}` | `{ reference, external_reference, amount, currency, phone, status }` |
|
|
80
|
+
| `GET /v1/transactions?external_reference=...` | idem, ou `404` |
|
|
81
|
+
| Notification | `POST callback_url`, en-tête `x-signature` = HMAC-SHA256 hexadécimal du corps brut avec le secret |
|
|
82
|
+
|
|
83
|
+
Statuts : `PENDING`, `SUCCESSFUL`, `FAILED`. Montants : entiers. Numéros : `2376XXXXXXXX`.
|
|
84
|
+
|
|
85
|
+
## Limites (à connaître avant d'en parler)
|
|
86
|
+
|
|
87
|
+
- Dialectes disponibles : CamPay et générique. Notch Pay et MTN MoMo sont les prochains. Pour un autre fournisseur, ta logique se teste via un adaptateur vers le format générique.
|
|
88
|
+
- Le dialecte CamPay est construit à partir de SDK publics, pas d'un accès à CamPay : les points « à confirmer » ci-dessus doivent être validés sur un compte de démo avant de s'y fier à 100 %.
|
|
89
|
+
- Les versements (payouts) ne sont pas encore simulés.
|
|
90
|
+
- 9/9 ne prouve pas l'absence de bug ; 1 échec prouve qu'il y en a un.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Lanceur de scénarios de pannes. Usage : node chaos.mjs chaos.config.json
|
|
3
|
+
// Il démarre le faux fournisseur, attaque ton appli avec les pannes réelles du mobile money,
|
|
4
|
+
// et écrit chaos-report.md. Code de sortie 1 si un scénario échoue.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import { startSimulator } from './simulateur.mjs';
|
|
7
|
+
|
|
8
|
+
const cfg = JSON.parse(fs.readFileSync(process.argv[2] || 'chaos.config.json', 'utf8'));
|
|
9
|
+
const P = cfg.provider, M = cfg.merchant;
|
|
10
|
+
const S = `http://localhost:${P.port}`;
|
|
11
|
+
const paid = s => (M.paidStates || ['PAID']).includes(s);
|
|
12
|
+
const review = s => (M.reviewStates || ['NEEDS_REVIEW']).includes(s);
|
|
13
|
+
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
14
|
+
const fmt = n => n.toLocaleString('fr-FR').replace(/ /g, ' ') + ' FCFA';
|
|
15
|
+
|
|
16
|
+
async function call(method, url, body) {
|
|
17
|
+
try {
|
|
18
|
+
const r = await fetch(url, { method, headers: { 'content-type': 'application/json' }, body: body ? JSON.stringify(body) : undefined });
|
|
19
|
+
let json = null; try { json = await r.json(); } catch { }
|
|
20
|
+
return { status: r.status, json };
|
|
21
|
+
} catch (e) { return { status: 0, error: e.message }; }
|
|
22
|
+
}
|
|
23
|
+
const fill = (tpl, o) => tpl.replace('{orderId}', encodeURIComponent(o.orderId));
|
|
24
|
+
let seq = 0;
|
|
25
|
+
const newOrder = () => ({ orderId: `ord_${Date.now()}_${++seq}`, phone: '2376' + String(10000000 + Math.floor(Math.random() * 89999999)), amount: 5000 });
|
|
26
|
+
const plan = (o, p) => call('POST', `${S}/_admin/plan`, { phone: o.phone, plan: p });
|
|
27
|
+
const pay = o => call('POST', M.payUrl, { orderId: o.orderId, amount: o.amount, phone: o.phone });
|
|
28
|
+
const state = async o => (await call('GET', fill(M.orderUrl, o))).json?.status ?? 'INCONNU';
|
|
29
|
+
const prov = async o => (await call('GET', `${S}/_admin/phone/${o.phone}`)).json;
|
|
30
|
+
const ref = async o => (await prov(o)).transactions[0]?.reference;
|
|
31
|
+
const reconcile = async () => M.reconcileUrl ? call('POST', M.reconcileUrl) : sleep(M.reconcileWaitMs || 0);
|
|
32
|
+
const effects = async o => M.effectsUrl ? (await call('GET', fill(M.effectsUrl, o))).json?.count ?? null : null;
|
|
33
|
+
|
|
34
|
+
const scenarios = [
|
|
35
|
+
{ id: 'double-clic', titre: 'Double clic simultané sur « Payer »', risque: 'client débité deux fois',
|
|
36
|
+
async run(o) { await plan(o, {}); await Promise.all([pay(o), pay(o)]); await sleep(700);
|
|
37
|
+
const d = (await prov(o)).debits, st = await state(o);
|
|
38
|
+
return { ok: d <= 1 && paid(st), detail: `${d} débit(s), commande ${st}`, perte: Math.max(0, d - 1) * o.amount }; } },
|
|
39
|
+
|
|
40
|
+
{ id: 'reponse-perdue', titre: 'Réponse de l\'opérateur perdue, le client réessaie', risque: 'double débit après coupure réseau',
|
|
41
|
+
async run(o) { await plan(o, { dropResponses: 1 }); await pay(o); await sleep(300); await pay(o); await sleep(700); await reconcile(); await sleep(300);
|
|
42
|
+
const d = (await prov(o)).debits, st = await state(o);
|
|
43
|
+
return { ok: d <= 1 && paid(st), detail: `${d} débit(s), commande ${st}`, perte: Math.max(0, d - 1) * o.amount + (paid(st) ? 0 : o.amount) }; } },
|
|
44
|
+
|
|
45
|
+
{ id: 'notification-perdue', titre: 'Notification de paiement jamais reçue', risque: 'client débité sans être servi',
|
|
46
|
+
async run(o) { await plan(o, { webhook: 'none' }); await pay(o); await sleep(700); await reconcile(); await sleep(300);
|
|
47
|
+
const st = await state(o);
|
|
48
|
+
return { ok: paid(st), detail: `opérateur : réussi, commande ${st}`, perte: paid(st) ? 0 : o.amount }; } },
|
|
49
|
+
|
|
50
|
+
{ id: 'notification-x20', titre: 'Même notification reçue 20 fois en même temps', risque: 'livraison ou crédit en double',
|
|
51
|
+
async run(o) { await plan(o, { webhook: 'none' }); await pay(o); await sleep(600);
|
|
52
|
+
await call('POST', `${S}/_admin/webhook`, { reference: await ref(o), times: 20, concurrent: true }); await sleep(500);
|
|
53
|
+
const st = await state(o), e = await effects(o);
|
|
54
|
+
if (e === null) return { ok: null, detail: `commande ${st} ; effets non mesurables (ajoute effectsUrl)`, perte: 0 };
|
|
55
|
+
return { ok: paid(st) && e === 1, detail: `${e} livraison(s), commande ${st}`, perte: Math.max(0, e - 1) * o.amount }; } },
|
|
56
|
+
|
|
57
|
+
{ id: 'fausse-signature', titre: 'Fausse notification « réussi » (signature invalide)', risque: 'livraison sans paiement',
|
|
58
|
+
async run(o) { await plan(o, { manual: true }); await pay(o); await sleep(300);
|
|
59
|
+
await call('POST', `${S}/_admin/webhook`, { reference: await ref(o), status: 'SUCCESSFUL', forge: true }); await sleep(300);
|
|
60
|
+
const st = await state(o);
|
|
61
|
+
return { ok: !paid(st), detail: `opérateur : en attente, commande ${st}`, perte: paid(st) ? o.amount : 0 }; } },
|
|
62
|
+
|
|
63
|
+
{ id: 'notification-menteuse', titre: 'Notification signée « réussi » alors que l\'opérateur dit « en attente »', risque: 'livraison sans paiement (rejeu, fuite de clé)',
|
|
64
|
+
async run(o) { await plan(o, { manual: true }); await pay(o); await sleep(300);
|
|
65
|
+
await call('POST', `${S}/_admin/webhook`, { reference: await ref(o), status: 'SUCCESSFUL' }); await sleep(300);
|
|
66
|
+
const st = await state(o);
|
|
67
|
+
return { ok: !paid(st), detail: `opérateur : en attente, commande ${st}`, perte: paid(st) ? o.amount : 0 }; } },
|
|
68
|
+
|
|
69
|
+
{ id: 'montant-different', titre: 'Le montant réellement payé est de 50 FCFA au lieu de 5 000', risque: 'produit livré pour presque rien',
|
|
70
|
+
async run(o) { await plan(o, { reportedAmount: 50 }); await pay(o); await sleep(700); await reconcile(); await sleep(300);
|
|
71
|
+
const st = await state(o);
|
|
72
|
+
return { ok: !paid(st), detail: `commande ${st}`, perte: paid(st) ? o.amount - 50 : 0 }; } },
|
|
73
|
+
|
|
74
|
+
{ id: 'echec-apres-succes', titre: 'Notification « échoué » reçue après un succès', risque: 'commande payée annulée par erreur',
|
|
75
|
+
async run(o) { await plan(o, {}); await pay(o); await sleep(700);
|
|
76
|
+
await call('POST', `${S}/_admin/webhook`, { reference: await ref(o), status: 'FAILED' }); await sleep(300);
|
|
77
|
+
const st = await state(o);
|
|
78
|
+
return { ok: paid(st), detail: `opérateur : réussi, commande ${st}`, perte: paid(st) ? 0 : o.amount }; } },
|
|
79
|
+
|
|
80
|
+
{ id: 'succes-tardif', titre: 'Le client valide après l\'expiration côté appli', risque: 'client débité, commande expirée en silence',
|
|
81
|
+
async run(o) { if (!M.forceExpiryUrl) return { ok: null, detail: 'non testé (ajoute forceExpiryUrl)', perte: 0 };
|
|
82
|
+
await plan(o, { manual: true }); await pay(o); await sleep(300); await call('POST', M.forceExpiryUrl); await sleep(200);
|
|
83
|
+
await call('POST', `${S}/_admin/settle`, { reference: await ref(o), status: 'SUCCESSFUL' }); await sleep(300); await reconcile(); await sleep(300);
|
|
84
|
+
const st = await state(o);
|
|
85
|
+
return { ok: paid(st) || review(st), detail: `opérateur : réussi, commande ${st}`, perte: paid(st) || review(st) ? 0 : o.amount }; } },
|
|
86
|
+
{ id: 'jeton-expire', titre: 'Jeton d\'accès expiré pendant l\'activité', risque: 'paiements impossibles jusqu\'au redémarrage',
|
|
87
|
+
async run(o) { if (P.dialect !== 'campay') return { ok: null, detail: 'sans objet pour ce dialecte', perte: 0 };
|
|
88
|
+
await plan(o, {}); await call('POST', `${S}/_admin/expire-tokens`); await pay(o); await sleep(700);
|
|
89
|
+
const d = (await prov(o)).debits, st = await state(o);
|
|
90
|
+
return { ok: d === 1 && paid(st), detail: `${d} débit(s), commande ${st}`, perte: paid(st) ? 0 : o.amount }; } },
|
|
91
|
+
];
|
|
92
|
+
|
|
93
|
+
const probe = await call('GET', fill(M.orderUrl, { orderId: 'verification_connexion' }));
|
|
94
|
+
if (probe.status === 0) {
|
|
95
|
+
console.error(`✘ Ton appli ne répond pas sur ${M.orderUrl} (${probe.error}). Démarre-la avant le crash-test.`);
|
|
96
|
+
process.exit(2);
|
|
97
|
+
}
|
|
98
|
+
const sim = await startSimulator(P);
|
|
99
|
+
const results = [];
|
|
100
|
+
for (const s of scenarios) {
|
|
101
|
+
const o = newOrder();
|
|
102
|
+
let r; try { r = await s.run(o); } catch (e) { r = { ok: false, detail: 'erreur : ' + e.message, perte: 0 }; }
|
|
103
|
+
results.push({ ...s, ...r });
|
|
104
|
+
console.log(`${r.ok === null ? '·' : r.ok ? '✔' : '✘'} ${s.titre} → ${r.detail}`);
|
|
105
|
+
}
|
|
106
|
+
await sim.close();
|
|
107
|
+
|
|
108
|
+
const fails = results.filter(r => r.ok === false), tested = results.filter(r => r.ok !== null);
|
|
109
|
+
const perte = fails.reduce((s, r) => s + r.perte, 0);
|
|
110
|
+
const lines = [
|
|
111
|
+
`# Rapport de crash-test mobile money`, '', `Dialecte : ${P.dialect || 'generic'} — ${new Date().toISOString().slice(0, 10)}`, '',
|
|
112
|
+
`**${tested.length - fails.length}/${tested.length} scénarios réussis.** Perte simulée sur ${tested.length} commandes de 5 000 FCFA : **${fmt(perte)}**.`, '',
|
|
113
|
+
'| Résultat | Scénario | Ce qui s\'est passé | Risque si ça échoue |', '|---|---|---|---|',
|
|
114
|
+
...results.map(r => `| ${r.ok === null ? 'non testé' : r.ok ? 'réussi' : '**échec**'} | ${r.titre} | ${r.detail} | ${r.risque} |`), '',
|
|
115
|
+
fails.length ? `Corrections : voir \`references/core/concurrence-et-incertitude.md\` et \`references/core/idempotence.md\`.` : 'Aucune faille détectée sur ces scénarios.',
|
|
116
|
+
];
|
|
117
|
+
fs.writeFileSync(cfg.report || 'chaos-report.md', lines.join('\n') + '\n');
|
|
118
|
+
if (cfg.badge) {
|
|
119
|
+
const ok = tested.length - fails.length, color = fails.length === 0 ? '#1a7f37' : ok / tested.length >= 0.7 ? '#bf8700' : '#cf222e';
|
|
120
|
+
const left = 'crash-test paiements', right = `${ok}/${tested.length}`, lw = 142, rw = 44;
|
|
121
|
+
fs.writeFileSync(cfg.badge, `<svg xmlns="http://www.w3.org/2000/svg" width="${lw + rw}" height="20" role="img" aria-label="${left}: ${right}"><title>${left}: ${right}</title><rect width="${lw}" height="20" fill="#555"/><rect x="${lw}" width="${rw}" height="20" fill="${color}"/><g fill="#fff" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11" text-anchor="middle"><text x="${lw / 2}" y="14">${left}</text><text x="${lw + rw / 2}" y="14">${right}</text></g></svg>\n`);
|
|
122
|
+
}
|
|
123
|
+
console.log(`\n${tested.length - fails.length}/${tested.length} réussis — perte simulée : ${fmt(perte)} — rapport : ${cfg.report || 'chaos-report.md'}`);
|
|
124
|
+
process.exit(fails.length ? 1 : 0);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="186" height="20" role="img" aria-label="crash-test paiements: 1/10"><title>crash-test paiements: 1/10</title><rect width="142" height="20" fill="#555"/><rect x="142" width="44" height="20" fill="#cf222e"/><g fill="#fff" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11" text-anchor="middle"><text x="71" y="14">crash-test paiements</text><text x="164" y="14">1/10</text></g></svg>
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="186" height="20" role="img" aria-label="crash-test paiements: 10/10"><title>crash-test paiements: 10/10</title><rect width="142" height="20" fill="#555"/><rect x="142" width="44" height="20" fill="#1a7f37"/><g fill="#fff" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11" text-anchor="middle"><text x="71" y="14">crash-test paiements</text><text x="164" y="14">10/10</text></g></svg>
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Intégration CamPay NAÏVE, telle qu'on en trouve souvent : elle marche en démo. NE PAS COPIER.
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
|
|
4
|
+
const CAMPAY = process.env.CAMPAY_URL || 'http://localhost:4010';
|
|
5
|
+
const USER = process.env.CAMPAY_USERNAME || 'app_user', PASS = process.env.CAMPAY_PASSWORD || 'app_pass';
|
|
6
|
+
const PORT = Number(process.env.PORT || 4030);
|
|
7
|
+
const orders = new Map(), byRef = new Map(), effects = new Map();
|
|
8
|
+
let token = null; // ❌ jeton obtenu une fois, jamais renouvelé
|
|
9
|
+
|
|
10
|
+
async function getToken() {
|
|
11
|
+
if (token) return token;
|
|
12
|
+
const r = await fetch(`${CAMPAY}/api/token/`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: USER, password: PASS }) });
|
|
13
|
+
return token = (await r.json()).token;
|
|
14
|
+
}
|
|
15
|
+
const read = req => new Promise(r => { let b = ''; req.on('data', c => b += c); req.on('end', () => r(b)); });
|
|
16
|
+
const send = (res, c, o) => { res.writeHead(c, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); };
|
|
17
|
+
|
|
18
|
+
http.createServer(async (req, res) => {
|
|
19
|
+
const url = new URL(req.url, 'http://x'), path = url.pathname;
|
|
20
|
+
|
|
21
|
+
if (req.method === 'POST' && path === '/pay') {
|
|
22
|
+
const { orderId, amount, phone } = JSON.parse(await read(req));
|
|
23
|
+
const o = orders.get(orderId);
|
|
24
|
+
if (o && o.status === 'PAID') return send(res, 200, o); // ❌ vérifier puis agir
|
|
25
|
+
try {
|
|
26
|
+
const r = await fetch(`${CAMPAY}/api/collect/`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Token ${await getToken()}` },
|
|
27
|
+
body: JSON.stringify({ amount: String(amount), currency: 'XAF', from: phone, description: 'Commande' }) }); // ❌ pas d'external_reference
|
|
28
|
+
if (r.status !== 200) return send(res, 502, { error: 'Paiement impossible' });
|
|
29
|
+
const j = await r.json();
|
|
30
|
+
orders.set(orderId, { orderId, status: 'PENDING', reference: j.reference }); byRef.set(j.reference, orderId);
|
|
31
|
+
return send(res, 202, { status: 'PENDING' });
|
|
32
|
+
} catch { return send(res, 502, { error: 'Erreur, réessayez' }); }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (path === '/webhook') {
|
|
36
|
+
const q = Object.fromEntries(url.searchParams); // ❌ signature ignorée, statut et montant crus sur parole
|
|
37
|
+
const o = orders.get(byRef.get(q.reference));
|
|
38
|
+
if (o) {
|
|
39
|
+
if (q.status === 'SUCCESSFUL') { o.status = 'PAID'; effects.set(o.orderId, (effects.get(o.orderId) || 0) + 1); }
|
|
40
|
+
if (q.status === 'FAILED') o.status = 'FAILED';
|
|
41
|
+
}
|
|
42
|
+
return send(res, 200, {});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (req.method === 'POST' && (path === '/_test/reconcile' || path === '/_test/force-expiry')) {
|
|
46
|
+
for (const o of orders.values()) if (o.status === 'PENDING') o.status = 'EXPIRED'; // ❌ attente = échec
|
|
47
|
+
return send(res, 200, {});
|
|
48
|
+
}
|
|
49
|
+
if (req.method === 'GET' && path.startsWith('/orders/')) return send(res, 200, orders.get(decodeURIComponent(path.split('/').pop())) || { status: 'INCONNU' });
|
|
50
|
+
if (req.method === 'GET' && path.startsWith('/_test/effects/')) return send(res, 200, { count: effects.get(decodeURIComponent(path.split('/').pop())) || 0 });
|
|
51
|
+
send(res, 404, {});
|
|
52
|
+
}).listen(PORT, () => console.log(`Intégration CamPay naïve sur http://localhost:${PORT}`));
|