daraja-reliable 0.0.0-stage → 0.1.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 +328 -2
- package/dist/adapters/fetch.d.ts +22 -0
- package/dist/adapters/fetch.js +121 -0
- package/dist/adapters/kepas.d.ts +32 -0
- package/dist/adapters/kepas.js +60 -0
- package/dist/callback.d.ts +13 -0
- package/dist/callback.js +43 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +8 -0
- package/dist/ip.d.ts +7 -0
- package/dist/ip.js +56 -0
- package/dist/pg-store.d.ts +46 -0
- package/dist/pg-store.js +179 -0
- package/dist/reliable.d.ts +178 -0
- package/dist/reliable.js +425 -0
- package/dist/state.d.ts +44 -0
- package/dist/state.js +75 -0
- package/dist/store.d.ts +149 -0
- package/dist/store.js +1 -0
- package/dist/testing/fake-daraja.d.ts +63 -0
- package/dist/testing/fake-daraja.js +125 -0
- package/dist/transport.d.ts +30 -0
- package/dist/transport.js +6 -0
- package/migrations/001_init.sql +39 -0
- package/migrations/002_receipt.sql +5 -0
- package/migrations/003_outbox.sql +16 -0
- package/migrations/004_retry.sql +8 -0
- package/package.json +69 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 daraja-reliable contributors
|
|
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,329 @@
|
|
|
1
|
-
#
|
|
1
|
+
# daraja-reliable
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Idempotency, replay protection and reconciliation for M-Pesa STK Push, above any Daraja SDK.
|
|
4
|
+
|
|
5
|
+
STK Push is asynchronous, and three facts about it decide the design:
|
|
6
|
+
|
|
7
|
+
1. **Safaricom never retries a callback.** If your endpoint is down, restarting, or
|
|
8
|
+
deployed mid-request, the result of that payment is gone. Nothing will resend it.
|
|
9
|
+
2. **STK Push accepts no caller-supplied correlation id.** `CheckoutRequestID` exists only
|
|
10
|
+
in the push *response*. Lose the response and you hold a payment prompt on a
|
|
11
|
+
customer's phone that you cannot identify, query, or ever bind a callback to.
|
|
12
|
+
3. **A failed callback carries no `MpesaReceiptNumber`.** Any dedupe scheme keyed on the
|
|
13
|
+
receipt silently does nothing for the failure path.
|
|
14
|
+
|
|
15
|
+
Existing Daraja SDKs wrap the HTTP API correctly and stop there. This library is the layer
|
|
16
|
+
above: it owns a charge's lifecycle in Postgres so that a prompt is sent at most once, a
|
|
17
|
+
callback is applied exactly once however many times it is delivered, and a payment whose
|
|
18
|
+
outcome is genuinely unknowable ends up in front of a person instead of being guessed at.
|
|
19
|
+
|
|
20
|
+
## Status
|
|
21
|
+
|
|
22
|
+
**v0, not published to npm.** Usable, but read this list before depending on it.
|
|
23
|
+
|
|
24
|
+
| | |
|
|
25
|
+
|---|---|
|
|
26
|
+
| Initiation, idempotency, crash recovery | built, tested |
|
|
27
|
+
| Callback handling, replay protection, origin allowlist | built, tested |
|
|
28
|
+
| Postgres store with compare-and-set transitions and leases | built, tested |
|
|
29
|
+
| Transports: raw `fetch`, `@kepas/daraja-js` adapter | built, tested |
|
|
30
|
+
| Reconciler sweep (`reconcile()`): resolves charges whose callback never arrived | built, tested |
|
|
31
|
+
| Transactional outbox and at-least-once event delivery (`on()` / `dispatch()`) | built, tested |
|
|
32
|
+
| `chargeAgain()`: a deliberate re-push after an ambiguous outcome | built, tested |
|
|
33
|
+
|
|
34
|
+
147 tests, property tests under [fast-check](https://github.com/dubzzz/fast-check), and the
|
|
35
|
+
state machine is mutation-checked — deleting a guard has to fail a named test or the test
|
|
36
|
+
is decoration. The reconciler and outbox are checked with [Stryker](https://stryker-mutator.io)
|
|
37
|
+
(`npx stryker run`, needs `DATABASE_URL`): 90.5% mutation score over that code, with the
|
|
38
|
+
survivors listed in [DESIGN.md](DESIGN.md) and each one explained. Integration tests run against a real Postgres, because row locking is the
|
|
39
|
+
thing under test and a mock would prove nothing.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
npm install daraja-reliable pg
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Requires Node 20+ and PostgreSQL 13+ (the migration uses the built-in `gen_random_uuid()`).
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import pg from 'pg';
|
|
53
|
+
import { createReliableDaraja, PostgresStore, migrate, fetchAdapter } from 'daraja-reliable';
|
|
54
|
+
|
|
55
|
+
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
|
|
56
|
+
await migrate(pool); // creates dr_charges, dr_audit and dr_outbox; idempotent. Run it after upgrading too.
|
|
57
|
+
|
|
58
|
+
const pesa = createReliableDaraja({
|
|
59
|
+
store: new PostgresStore(pool),
|
|
60
|
+
transport: fetchAdapter({
|
|
61
|
+
consumerKey: process.env.DARAJA_KEY!,
|
|
62
|
+
consumerSecret: process.env.DARAJA_SECRET!,
|
|
63
|
+
shortcode: process.env.DARAJA_SHORTCODE!,
|
|
64
|
+
passkey: process.env.DARAJA_PASSKEY!,
|
|
65
|
+
callbackUrl: 'https://your.app/mpesa/callback',
|
|
66
|
+
environment: 'production',
|
|
67
|
+
}),
|
|
68
|
+
// Safaricom's current callback source IPs. This library deliberately ships no list,
|
|
69
|
+
// because a stale hardcoded one fails closed at 3am. 'disabled' is allowed, and has
|
|
70
|
+
// to be written out so the choice is visible in your code.
|
|
71
|
+
trustedSourceIps: ['196.201.214.0/24'],
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Charging
|
|
76
|
+
|
|
77
|
+
`idempotencyKey` is yours — an invoice id, an order id, anything stable for the payment
|
|
78
|
+
you mean to collect. Call it as many times as you like; the customer is prompted once.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const charge = await pesa.charge({
|
|
82
|
+
idempotencyKey: 'invoice-4821',
|
|
83
|
+
phone: '254712345678', // E.164 digits, no '+'
|
|
84
|
+
amount: 1500, // whole KES
|
|
85
|
+
accountRef: 'INV-4821',
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
charge.state; // 'awaiting_callback' | 'push_unknown' | 'failed'
|
|
89
|
+
charge.replayed; // true if this key was already known and nothing was sent
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Reusing a key with different parameters throws `IdempotencyConflictError` rather than
|
|
93
|
+
returning the original charge, because that mismatch is a bug in the caller and silently
|
|
94
|
+
returning the wrong charge would hide it.
|
|
95
|
+
|
|
96
|
+
### The callback route
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
app.post('/mpesa/callback', async (req, res) => {
|
|
100
|
+
const result = await pesa.handleCallback({
|
|
101
|
+
rawBody: req.rawBody, // the EXACT bytes; do not let a body parser touch them first
|
|
102
|
+
sourceIp: req.socket.remoteAddress!,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
res.sendStatus(200); // always 200: Safaricom will not retry, so a 500 loses the payment
|
|
106
|
+
if (result.applied) await fulfilOrder(result.charge!);
|
|
107
|
+
});
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`handleCallback` resolves for every input a real endpoint receives — wrong IP, malformed
|
|
111
|
+
body, unknown id, tenth duplicate — so the route can always answer 200. `applied` is true
|
|
112
|
+
for exactly one delivery of a given outcome: the one that moved the charge. Do your
|
|
113
|
+
fulfilment behind that flag and it runs once.
|
|
114
|
+
|
|
115
|
+
Two details that matter more than they look:
|
|
116
|
+
|
|
117
|
+
- **`rawBody` must be the unparsed request bytes.** The raw payload is retained for replay
|
|
118
|
+
and for the audit trail, and a re-serialised body is not what Safaricom sent.
|
|
119
|
+
- **`sourceIp` must be the real peer address.** Behind a proxy, `req.ip` is the proxy
|
|
120
|
+
unless trust-proxy is configured correctly — get it wrong and the allowlist either
|
|
121
|
+
rejects every genuine callback or trusts a spoofed `X-Forwarded-For`.
|
|
122
|
+
|
|
123
|
+
### Crash recovery
|
|
124
|
+
|
|
125
|
+
A process that dies between writing the intent and recording the push outcome leaves a
|
|
126
|
+
`pending` row. `recover()` moves those to `push_unknown`. It never re-pushes.
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
// On boot, and on a schedule. olderThanMs MUST exceed your transport's total timeout:
|
|
130
|
+
// a charge is `pending` for as long as its push is in flight. Minutes, not seconds.
|
|
131
|
+
const stranded = await pesa.recover({ olderThanMs: 5 * 60_000 });
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Reconciliation
|
|
135
|
+
|
|
136
|
+
Safaricom never retries a callback, so a charge whose callback was lost sits in
|
|
137
|
+
`awaiting_callback` forever unless something asks. `reconcile()` asks. Run it on a schedule.
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
// Every minute or so. Safe to run from several processes at once: each overdue charge is
|
|
141
|
+
// leased to one sweeper, so two reconcilers never resolve the same charge twice.
|
|
142
|
+
const r = await pesa.reconcile({ limit: 100, concurrency: 5 });
|
|
143
|
+
// { checked, settled, failed, unresolved, stillWaiting, discrepancies, errors }
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
For every charge past `callbackDeadlineMs` (default 4 minutes) it calls STK Push Query:
|
|
147
|
+
|
|
148
|
+
- A definite answer settles or fails the charge, through the same compare-and-set a callback
|
|
149
|
+
uses, so a callback and a sweep racing each other still produce one transition.
|
|
150
|
+
- "Still processing" leaves it alone.
|
|
151
|
+
- A query that errors is not held against the charge until it is older than
|
|
152
|
+
`callbackDeadlineMs + failureGraceMs`. After three such failures it becomes `unresolved`.
|
|
153
|
+
- A `push_unknown` charge has nothing to query, so it goes straight to `unresolved` for a
|
|
154
|
+
person. It is never guessed at.
|
|
155
|
+
- If the query contradicts a callback that already settled the charge, nothing is
|
|
156
|
+
overwritten. A `discrepancy` event is raised so a person looks.
|
|
157
|
+
|
|
158
|
+
### Events
|
|
159
|
+
|
|
160
|
+
Every outcome that needs something to happen next — fulfil an order, refund, page a human —
|
|
161
|
+
is written to an outbox **in the same SQL statement as the transition**. The event exists if
|
|
162
|
+
and only if the transition committed; there is no window where the charge moved and the
|
|
163
|
+
event was lost, or the event exists for a move that rolled back.
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
pesa.on('settled', async (charge, meta) => {
|
|
167
|
+
// meta: { type, detail, attempt }. attempt is 1 on first delivery, 2+ on redelivery.
|
|
168
|
+
await fulfilOrder(charge);
|
|
169
|
+
});
|
|
170
|
+
pesa.on('unresolved', async (charge) => pageSomeone(charge));
|
|
171
|
+
pesa.on('discrepancy', async (charge, meta) => pageSomeone(charge, meta.detail));
|
|
172
|
+
|
|
173
|
+
await pesa.dispatch(); // also runs at the end of every reconcile()
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Event types: `settled`, `failed`, `unresolved`, `discrepancy`.
|
|
177
|
+
|
|
178
|
+
Delivery is **at-least-once**. A handler that throws keeps its event, and it is redelivered
|
|
179
|
+
after `redeliveryDelayMs` (default 30 s) with `attempt` incremented. So a handler can run
|
|
180
|
+
twice for one event and **must be idempotent** — key your fulfilment on `charge.id`. If no
|
|
181
|
+
handler is registered for a type, its events stay queued rather than being consumed, so a
|
|
182
|
+
process that starts later still delivers them. Concurrent dispatchers deliver each event to
|
|
183
|
+
one claimer at a time.
|
|
184
|
+
|
|
185
|
+
### Charging again
|
|
186
|
+
|
|
187
|
+
A charge in `push_unknown` (the response was lost) or `unresolved` (nothing could say) may or may
|
|
188
|
+
not have put a prompt on the customer's phone. The library never re-pushes on its own. When you
|
|
189
|
+
decide a second prompt is better than leaving the customer waiting, you ask for it:
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
const again = await pesa.chargeAgain(charge.id, { acknowledgeDuplicateRisk: true });
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The flag has to be the literal `true`, because this is the one call that can take a customer's
|
|
196
|
+
money twice: if the first prompt was live and they pay both, you have both payments.
|
|
197
|
+
|
|
198
|
+
- **It is a new charge, not a change to the old one.** It has its own row and its own
|
|
199
|
+
`CheckoutRequestID`, linked by `charge.rootId` (the first charge of the chain; `null` for a
|
|
200
|
+
charge that was never retried). A late callback for the *old* prompt still binds to the old
|
|
201
|
+
charge. The old charge is left exactly as it was. If it holds an id, a late callback can still
|
|
202
|
+
settle it; if it never had one, it stays `push_unknown` / `unresolved`. The library has no
|
|
203
|
+
public call for resolving a charge by hand yet (the state machine has the edge, the API does
|
|
204
|
+
not expose it), so that decision lives in your own records for now.
|
|
205
|
+
- **It is idempotent.** Asking again for the same charge returns the same retry with
|
|
206
|
+
`replayed: true` and never prompts a third time, even when callers race. To retry the retry,
|
|
207
|
+
call `chargeAgain` on the retry; `attempt` counts them.
|
|
208
|
+
- **It refuses anything else.** `awaiting_callback` has a live prompt the reconciler is already
|
|
209
|
+
chasing, `pending` may still be in flight, `settled` was paid, and `failed` is a definite
|
|
210
|
+
answer, so a retry of a refusal is just a new `charge()` of yours. They throw
|
|
211
|
+
`NotRetryableError` and write nothing.
|
|
212
|
+
- **If both prompts are paid, you are told.** Both charges settle; the second one to do so
|
|
213
|
+
raises a `discrepancy` event with `reason: 'duplicate_payment'` and the id of the other.
|
|
214
|
+
Nothing is reversed, because only you can refund.
|
|
215
|
+
|
|
216
|
+
Because a payment can now be prompted twice, **fulfil on `charge.rootId ?? charge.id`**, not on
|
|
217
|
+
`charge.id`, or one payment that was prompted twice and paid once could be fulfilled twice.
|
|
218
|
+
|
|
219
|
+
One window cannot be closed: the old charge can settle while the retry's push is on the wire,
|
|
220
|
+
because Safaricom may deliver that callback at any moment. The `duplicate_payment` event is the
|
|
221
|
+
backstop for it.
|
|
222
|
+
|
|
223
|
+
`applied` from `handleCallback` is still the quickest way to fulfil from the callback route.
|
|
224
|
+
The outbox is what covers the cases it cannot: outcomes reached by the reconciler, and
|
|
225
|
+
processes that crash between the callback and the fulfilment.
|
|
226
|
+
|
|
227
|
+
## The state machine
|
|
228
|
+
|
|
229
|
+
Transitions live in one pure function, [`next(charge, event)`](src/state.ts), with the
|
|
230
|
+
legal edges as an explicit set. Nothing writes a state the function did not return.
|
|
231
|
+
|
|
232
|
+
```
|
|
233
|
+
┌──────────────────────────────► settled
|
|
234
|
+
│ ▲
|
|
235
|
+
pending ──► awaiting_callback ──────────────┐ │
|
|
236
|
+
│ │ │ │
|
|
237
|
+
│ └──► unresolved ─────────┼──────────┘
|
|
238
|
+
│ ▲ │
|
|
239
|
+
└──► push_unknown ────────┘ └────────► failed
|
|
240
|
+
│
|
|
241
|
+
└──► awaiting_callback (a late push response: identity recovered)
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
| State | Meaning |
|
|
245
|
+
|---|---|
|
|
246
|
+
| `pending` | Intent is durable; the push has not been accounted for yet |
|
|
247
|
+
| `awaiting_callback` | Safaricom accepted the push and we hold the `CheckoutRequestID` |
|
|
248
|
+
| `push_unknown` | The push may have reached the customer, but its response was lost — so there is no id to query with |
|
|
249
|
+
| `unresolved` | Out of automatic options. A person decides |
|
|
250
|
+
| `settled` / `failed` | Terminal. Nothing moves a charge out of these |
|
|
251
|
+
|
|
252
|
+
Two things it refuses to do, both deliberate:
|
|
253
|
+
|
|
254
|
+
**It will not settle a charge it cannot identify.** A `push_unknown` charge has no
|
|
255
|
+
`CheckoutRequestID`, so matching an incoming payment on `(phone, amount, accountRef)` is a
|
|
256
|
+
heuristic, not proof — two customers can pay the same amount against the same reference in
|
|
257
|
+
the same minute. Such a charge is resolvable only by `manual_resolve`. This is enforced
|
|
258
|
+
inside `next()`, where the property tests can reach it, rather than in calling code.
|
|
259
|
+
|
|
260
|
+
**It will not treat "accepted" as "paid."** A push Safaricom accepted is a prompt on a
|
|
261
|
+
phone, nothing more. Only a callback or a successful STK Push Query settles a charge.
|
|
262
|
+
|
|
263
|
+
### Identity is not state
|
|
264
|
+
|
|
265
|
+
The one bug found so far is worth describing, because the fix shaped the design.
|
|
266
|
+
|
|
267
|
+
`apply()` read a charge, decided with `next()`, then compare-and-set. On a CAS miss it gave
|
|
268
|
+
up. But **a CAS miss means the state moved, not that the event was inapplicable** — the
|
|
269
|
+
decision was made against a view that had since gone stale. That lost money two ways: a
|
|
270
|
+
successful push whose `CheckoutRequestID` was discarded because a recovery sweep had
|
|
271
|
+
overtaken it, and a callback dropped because it landed exactly as the reconciler gave up,
|
|
272
|
+
even though `next(unresolved, callback)` settles.
|
|
273
|
+
|
|
274
|
+
So a miss now re-reads and re-decides, and `checkoutRequestId` is persisted in its own
|
|
275
|
+
idempotent statement before any transition is attempted. It is *identity*, not state: the
|
|
276
|
+
only correlation id Safaricom ever issues, and it must not be able to die with a lost race.
|
|
277
|
+
|
|
278
|
+
Both cases are regression-tested in
|
|
279
|
+
[`test/integration/races.test.ts`](test/integration/races.test.ts). Full reasoning,
|
|
280
|
+
including where the first mutation run showed the tests had a hole, is in
|
|
281
|
+
[DESIGN.md](DESIGN.md).
|
|
282
|
+
|
|
283
|
+
## Testing your own integration
|
|
284
|
+
|
|
285
|
+
Safaricom's sandbox only exercises the happy path. `FakeDaraja` injects the failures that
|
|
286
|
+
only happen in production:
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
import { FakeDaraja } from 'daraja-reliable/testing';
|
|
290
|
+
|
|
291
|
+
const fake = new FakeDaraja();
|
|
292
|
+
fake.scriptPush('ok_but_response_lost'); // the customer IS prompted; you see a timeout
|
|
293
|
+
|
|
294
|
+
const pesa = createReliableDaraja({ transport: fake, store, trustedSourceIps: 'disabled' });
|
|
295
|
+
const charge = await pesa.charge({ idempotencyKey: 'test-1', ...req });
|
|
296
|
+
// charge.state === 'push_unknown', and a retry must not prompt the customer again
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
Behaviours: `ok`, `reject`, `http500`, `hang`, `ok_but_response_lost`. `callbackBody()`
|
|
300
|
+
builds payloads shaped like the real endpoint's.
|
|
301
|
+
|
|
302
|
+
## Development
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
npm install
|
|
306
|
+
docker run -d --name daraja-pg -e POSTGRES_PASSWORD=postgres -p 5433:5432 postgres:16-alpine
|
|
307
|
+
export DATABASE_URL=postgres://postgres:postgres@localhost:5433/postgres
|
|
308
|
+
|
|
309
|
+
npm run typecheck
|
|
310
|
+
npm test # unit + integration
|
|
311
|
+
npm run test:unit # no database needed
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Integration tests truncate `dr_charges` and `dr_audit` (and the outbox, by cascade) between
|
|
315
|
+
cases, so point `DATABASE_URL` at a throwaway database. Run them through `npm test`, which
|
|
316
|
+
serialises the files: they share one database and would truncate each other's rows if run
|
|
317
|
+
in parallel.
|
|
318
|
+
|
|
319
|
+
## Scope
|
|
320
|
+
|
|
321
|
+
This library runs entirely on **your** Daraja credentials and never holds, routes or
|
|
322
|
+
aggregates anyone's funds. That is a deliberate boundary: under CBK rules, handling or
|
|
323
|
+
aggregating customer money in Kenya requires a Payment Service Provider licence. A
|
|
324
|
+
reliability layer that merchants run themselves needs none, and this will not grow into
|
|
325
|
+
anything that does.
|
|
326
|
+
|
|
327
|
+
## Licence
|
|
328
|
+
|
|
329
|
+
[MIT](LICENSE).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Transport } from '../transport.js';
|
|
2
|
+
export interface FetchAdapterOptions {
|
|
3
|
+
consumerKey: string;
|
|
4
|
+
consumerSecret: string;
|
|
5
|
+
shortcode: string;
|
|
6
|
+
passkey: string;
|
|
7
|
+
callbackUrl: string;
|
|
8
|
+
environment: 'sandbox' | 'production';
|
|
9
|
+
description?: string;
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
fetch?: typeof fetch;
|
|
12
|
+
}
|
|
13
|
+
/** YYYYMMDDHHMMSS in UTC, zero padded. */
|
|
14
|
+
export declare function timestamp(d?: Date): string;
|
|
15
|
+
/** base64(shortcode + passkey + timestamp): order matters. */
|
|
16
|
+
export declare function password(shortcode: string, passkey: string, ts: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* Raw `fetch` transport. Mirrors the gotchas kepas documents: PartyA/PhoneNumber must be JSON
|
|
19
|
+
* numbers (strings silently 1037-time-out in production), UTC timestamp, password order.
|
|
20
|
+
* Never retries a push: a retry after an ambiguous failure could prompt the customer twice.
|
|
21
|
+
*/
|
|
22
|
+
export declare function fetchAdapter(o: FetchAdapterOptions): Transport;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { PushRejectedError, } from '../transport.js';
|
|
3
|
+
class HttpStatusError extends Error {
|
|
4
|
+
httpStatus;
|
|
5
|
+
constructor(httpStatus, body) {
|
|
6
|
+
super(`Daraja HTTP ${httpStatus}: ${body.slice(0, 200)}`);
|
|
7
|
+
this.httpStatus = httpStatus;
|
|
8
|
+
this.name = 'HttpStatusError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** YYYYMMDDHHMMSS in UTC, zero padded. */
|
|
12
|
+
export function timestamp(d = new Date()) {
|
|
13
|
+
const p = (n, w = 2) => String(n).padStart(w, '0');
|
|
14
|
+
return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`;
|
|
15
|
+
}
|
|
16
|
+
/** base64(shortcode + passkey + timestamp): order matters. */
|
|
17
|
+
export function password(shortcode, passkey, ts) {
|
|
18
|
+
return Buffer.from(`${shortcode}${passkey}${ts}`).toString('base64');
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Raw `fetch` transport. Mirrors the gotchas kepas documents: PartyA/PhoneNumber must be JSON
|
|
22
|
+
* numbers (strings silently 1037-time-out in production), UTC timestamp, password order.
|
|
23
|
+
* Never retries a push: a retry after an ambiguous failure could prompt the customer twice.
|
|
24
|
+
*/
|
|
25
|
+
export function fetchAdapter(o) {
|
|
26
|
+
const base = o.environment === 'production' ? 'https://api.safaricom.co.ke' : 'https://sandbox.safaricom.co.ke';
|
|
27
|
+
const doFetch = o.fetch ?? globalThis.fetch;
|
|
28
|
+
const timeoutMs = o.timeoutMs ?? 30_000;
|
|
29
|
+
let token = null;
|
|
30
|
+
async function call(path, init) {
|
|
31
|
+
const ctl = new AbortController();
|
|
32
|
+
const timer = setTimeout(() => ctl.abort(), timeoutMs);
|
|
33
|
+
try {
|
|
34
|
+
const res = await doFetch(`${base}${path}`, { ...init, signal: ctl.signal });
|
|
35
|
+
const text = await res.text();
|
|
36
|
+
if (!res.ok)
|
|
37
|
+
throw new HttpStatusError(res.status, text);
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(text);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new Error('Daraja returned a non-JSON 200 body'); // ambiguous: may have been queued
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function getToken() {
|
|
50
|
+
if (token && token.expires > Date.now() + 30_000)
|
|
51
|
+
return token.value;
|
|
52
|
+
const basic = Buffer.from(`${o.consumerKey}:${o.consumerSecret}`).toString('base64');
|
|
53
|
+
const r = (await call('/oauth/v1/generate?grant_type=client_credentials', {
|
|
54
|
+
method: 'GET',
|
|
55
|
+
headers: { authorization: `Basic ${basic}` },
|
|
56
|
+
}));
|
|
57
|
+
if (!r.access_token)
|
|
58
|
+
throw new HttpStatusError(401, 'no access_token in OAuth response');
|
|
59
|
+
token = { value: r.access_token, expires: Date.now() + Number(r.expires_in ?? 3599) * 1000 };
|
|
60
|
+
return token.value;
|
|
61
|
+
}
|
|
62
|
+
async function post(path, body) {
|
|
63
|
+
const t = await getToken();
|
|
64
|
+
return (await call(path, {
|
|
65
|
+
method: 'POST',
|
|
66
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${t}` },
|
|
67
|
+
body: JSON.stringify(body),
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
async stkPush(req) {
|
|
72
|
+
const ts = timestamp();
|
|
73
|
+
const phone = Number(req.phone);
|
|
74
|
+
let raw;
|
|
75
|
+
try {
|
|
76
|
+
raw = await post('/mpesa/stkpush/v1/processrequest', {
|
|
77
|
+
BusinessShortCode: o.shortcode,
|
|
78
|
+
Password: password(o.shortcode, o.passkey, ts),
|
|
79
|
+
Timestamp: ts,
|
|
80
|
+
TransactionType: 'CustomerPayBillOnline',
|
|
81
|
+
Amount: req.amount,
|
|
82
|
+
PartyA: phone,
|
|
83
|
+
PartyB: o.shortcode,
|
|
84
|
+
PhoneNumber: phone,
|
|
85
|
+
CallBackURL: o.callbackUrl,
|
|
86
|
+
AccountReference: req.accountRef,
|
|
87
|
+
TransactionDesc: o.description ?? 'Payment',
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
// 4xx (incl. 401) means Safaricom did not accept the request. 5xx, timeouts and
|
|
92
|
+
// network errors are ambiguous and propagate unchanged.
|
|
93
|
+
if (err instanceof HttpStatusError && err.httpStatus < 500)
|
|
94
|
+
throw new PushRejectedError(err.message);
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
97
|
+
if (raw.ResponseCode !== '0') {
|
|
98
|
+
throw new PushRejectedError(`ResponseCode ${String(raw.ResponseCode)}: ${String(raw.ResponseDescription ?? '')}`);
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
checkoutRequestId: String(raw.CheckoutRequestID ?? ''),
|
|
102
|
+
merchantRequestId: String(raw.MerchantRequestID ?? ''),
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
async stkQuery(checkoutRequestId) {
|
|
106
|
+
const ts = timestamp();
|
|
107
|
+
const raw = await post('/mpesa/stkpushquery/v1/query', {
|
|
108
|
+
BusinessShortCode: o.shortcode,
|
|
109
|
+
Password: password(o.shortcode, o.passkey, ts),
|
|
110
|
+
Timestamp: ts,
|
|
111
|
+
CheckoutRequestID: checkoutRequestId,
|
|
112
|
+
});
|
|
113
|
+
if (raw.ResultCode === undefined || raw.ResultCode === '')
|
|
114
|
+
return { status: 'processing' };
|
|
115
|
+
const code = Number(raw.ResultCode);
|
|
116
|
+
if (!Number.isFinite(code))
|
|
117
|
+
throw new Error(`unparseable ResultCode "${String(raw.ResultCode)}"`);
|
|
118
|
+
return { status: 'done', resultCode: code };
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Transport } from '../transport.js';
|
|
2
|
+
/**
|
|
3
|
+
* The slice of `@kepas/daraja-js` (^1.6) this adapter uses, as a structural type so the
|
|
4
|
+
* package is not a hard dependency. Pass `new Daraja({...})`.
|
|
5
|
+
*/
|
|
6
|
+
export interface KepasLike {
|
|
7
|
+
collect: {
|
|
8
|
+
stkPush(input: {
|
|
9
|
+
phone: string;
|
|
10
|
+
amount: number;
|
|
11
|
+
accountReference: string;
|
|
12
|
+
description: string;
|
|
13
|
+
callbackUrl: string;
|
|
14
|
+
}): Promise<{
|
|
15
|
+
checkoutRequestId: string;
|
|
16
|
+
merchantRequestId: string;
|
|
17
|
+
}>;
|
|
18
|
+
};
|
|
19
|
+
status: {
|
|
20
|
+
stkPush(input: {
|
|
21
|
+
checkoutRequestId: string;
|
|
22
|
+
}): Promise<{
|
|
23
|
+
responseCode: string;
|
|
24
|
+
resultCode: string;
|
|
25
|
+
}>;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export interface KepasAdapterOptions {
|
|
29
|
+
callbackUrl: string;
|
|
30
|
+
description?: string;
|
|
31
|
+
}
|
|
32
|
+
export declare function kepasAdapter(daraja: KepasLike, o: KepasAdapterOptions): Transport;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { PushRejectedError, } from '../transport.js';
|
|
2
|
+
/**
|
|
3
|
+
* Classify a thrown kepas error. kepas sets `error.name` to the class name, so we match on
|
|
4
|
+
* that instead of importing its classes (the HTTP error class is not exported).
|
|
5
|
+
*
|
|
6
|
+
* - refused before or by Safaricom, nothing in flight: validation, auth (401), 4xx,
|
|
7
|
+
* and DarajaAPIError (HTTP 200 with ResponseCode != 0)
|
|
8
|
+
* - anything else (5xx, timeout, network, unknown): ambiguous, so it is rethrown unchanged
|
|
9
|
+
* and the core records push_unknown.
|
|
10
|
+
*/
|
|
11
|
+
function classify(err) {
|
|
12
|
+
if (typeof err !== 'object' || err === null)
|
|
13
|
+
return 'ambiguous';
|
|
14
|
+
const e = err;
|
|
15
|
+
if (typeof e.httpStatus === 'number')
|
|
16
|
+
return e.httpStatus >= 500 ? 'ambiguous' : 'rejected';
|
|
17
|
+
switch (e.name) {
|
|
18
|
+
case 'DarajaValidationError':
|
|
19
|
+
case 'DarajaAuthError':
|
|
20
|
+
case 'DarajaAPIError':
|
|
21
|
+
case 'DarajaInsufficientFundsError':
|
|
22
|
+
case 'DarajaUserUnreachableError':
|
|
23
|
+
case 'DarajaCancelledError':
|
|
24
|
+
return 'rejected';
|
|
25
|
+
default:
|
|
26
|
+
return 'ambiguous'; // includes DarajaConnectionError and anything unrecognised
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function kepasAdapter(daraja, o) {
|
|
30
|
+
return {
|
|
31
|
+
async stkPush(req) {
|
|
32
|
+
try {
|
|
33
|
+
const r = await daraja.collect.stkPush({
|
|
34
|
+
phone: req.phone,
|
|
35
|
+
amount: req.amount,
|
|
36
|
+
accountReference: req.accountRef,
|
|
37
|
+
description: o.description ?? 'Payment',
|
|
38
|
+
callbackUrl: o.callbackUrl,
|
|
39
|
+
});
|
|
40
|
+
return { checkoutRequestId: r.checkoutRequestId, merchantRequestId: r.merchantRequestId };
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
if (classify(err) === 'rejected') {
|
|
44
|
+
throw new PushRejectedError(err instanceof Error ? err.message : 'push rejected');
|
|
45
|
+
}
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
async stkQuery(checkoutRequestId) {
|
|
50
|
+
const r = await daraja.status.stkPush({ checkoutRequestId });
|
|
51
|
+
// kepas returns ResultCode as a string. An empty one means no verdict yet.
|
|
52
|
+
if (r.resultCode === '')
|
|
53
|
+
return { status: 'processing' };
|
|
54
|
+
const code = Number(r.resultCode);
|
|
55
|
+
if (!Number.isFinite(code))
|
|
56
|
+
throw new Error(`unparseable ResultCode "${r.resultCode}"`);
|
|
57
|
+
return { status: 'done', resultCode: code };
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface ParsedCallback {
|
|
2
|
+
checkoutRequestId: string;
|
|
3
|
+
merchantRequestId: string | null;
|
|
4
|
+
resultCode: number;
|
|
5
|
+
/** Present only on success. Failed callbacks carry no receipt. */
|
|
6
|
+
receipt: string | null;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Parse Safaricom's STK callback from the RAW body. Returns null for anything that is not a
|
|
10
|
+
* well-formed STK callback; callers must still answer 200 and retain the raw payload.
|
|
11
|
+
* Pure: never throws.
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseStkCallback(raw: string): ParsedCallback | null;
|
package/dist/callback.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
2
|
+
/**
|
|
3
|
+
* Parse Safaricom's STK callback from the RAW body. Returns null for anything that is not a
|
|
4
|
+
* well-formed STK callback; callers must still answer 200 and retain the raw payload.
|
|
5
|
+
* Pure: never throws.
|
|
6
|
+
*/
|
|
7
|
+
export function parseStkCallback(raw) {
|
|
8
|
+
if (raw.length > MAX_BODY_BYTES)
|
|
9
|
+
return null;
|
|
10
|
+
let body;
|
|
11
|
+
try {
|
|
12
|
+
body = JSON.parse(raw);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
const stk = body?.Body?.stkCallback;
|
|
18
|
+
if (typeof stk !== 'object' || stk === null)
|
|
19
|
+
return null;
|
|
20
|
+
const cb = stk;
|
|
21
|
+
if (typeof cb.CheckoutRequestID !== 'string' || cb.CheckoutRequestID === '')
|
|
22
|
+
return null;
|
|
23
|
+
// Documented as a number, but accept a numeric string rather than lose a payment over it.
|
|
24
|
+
const code = typeof cb.ResultCode === 'string' && cb.ResultCode.trim() !== '' ? Number(cb.ResultCode) : cb.ResultCode;
|
|
25
|
+
if (typeof code !== 'number' || !Number.isInteger(code))
|
|
26
|
+
return null;
|
|
27
|
+
let receipt = null;
|
|
28
|
+
const items = cb.CallbackMetadata?.Item;
|
|
29
|
+
if (Array.isArray(items)) {
|
|
30
|
+
for (const it of items) {
|
|
31
|
+
const item = it;
|
|
32
|
+
if (item?.Name === 'MpesaReceiptNumber' && typeof item.Value === 'string' && item.Value !== '') {
|
|
33
|
+
receipt = item.Value;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
checkoutRequestId: cb.CheckoutRequestID,
|
|
39
|
+
merchantRequestId: typeof cb.MerchantRequestID === 'string' ? cb.MerchantRequestID : null,
|
|
40
|
+
resultCode: code,
|
|
41
|
+
receipt,
|
|
42
|
+
};
|
|
43
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { createReliableDaraja, IdempotencyConflictError, NotRetryableError, ValidationError, fingerprint } from './reliable.js';
|
|
2
|
+
export type { ChargeInput, ChargeAgainOptions, ChargeResult, CallbackInput, CallbackResult, CallbackReason, Reliable, ReliableOptions, ReconcileResult, DispatchResult, EventHandler, EventMeta } from './reliable.js';
|
|
3
|
+
export { buildIpMatcher } from './ip.js';
|
|
4
|
+
export { parseStkCallback } from './callback.js';
|
|
5
|
+
export type { ParsedCallback } from './callback.js';
|
|
6
|
+
export { next, TERMINAL, ALLOWED_EDGES, QUERY_FAILURE_LIMIT } from './state.js';
|
|
7
|
+
export type { State, Event, ChargeView } from './state.js';
|
|
8
|
+
export { PostgresStore, migrate } from './pg-store.js';
|
|
9
|
+
export type { Store, Charge, NewCharge, AuditEntry, OutboxEntry, OutboxType } from './store.js';
|
|
10
|
+
export { PushRejectedError } from './transport.js';
|
|
11
|
+
export type { Transport, StkPushRequest, StkPushResponse, StkQueryResponse } from './transport.js';
|
|
12
|
+
export { kepasAdapter } from './adapters/kepas.js';
|
|
13
|
+
export type { KepasLike, KepasAdapterOptions } from './adapters/kepas.js';
|
|
14
|
+
export { fetchAdapter } from './adapters/fetch.js';
|
|
15
|
+
export type { FetchAdapterOptions } from './adapters/fetch.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createReliableDaraja, IdempotencyConflictError, NotRetryableError, ValidationError, fingerprint } from './reliable.js';
|
|
2
|
+
export { buildIpMatcher } from './ip.js';
|
|
3
|
+
export { parseStkCallback } from './callback.js';
|
|
4
|
+
export { next, TERMINAL, ALLOWED_EDGES, QUERY_FAILURE_LIMIT } from './state.js';
|
|
5
|
+
export { PostgresStore, migrate } from './pg-store.js';
|
|
6
|
+
export { PushRejectedError } from './transport.js';
|
|
7
|
+
export { kepasAdapter } from './adapters/kepas.js';
|
|
8
|
+
export { fetchAdapter } from './adapters/fetch.js';
|