@astratra/shipping 0.0.0-stage → 1.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.fr.md +218 -0
- package/README.md +145 -2
- package/package.json +41 -4
- package/src/carrier.js +41 -0
- package/src/errors.js +80 -0
- package/src/index.d.ts +208 -0
- package/src/index.js +7 -0
- package/src/sendcloud.js +417 -0
- package/src/statuses.js +42 -0
- package/src/webhook.js +116 -0
package/src/webhook.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tracking webhook of a carrier, on @astratra/payments' webhook pipeline:
|
|
3
|
+
* raw-body signature check, atomic replay protection (claim → handle → record,
|
|
4
|
+
* release on failure), side effects that cannot fail the webhook.
|
|
5
|
+
*
|
|
6
|
+
* The event id is the SHA-256 of the raw body: Sendcloud resends the same body,
|
|
7
|
+
* so a resend is recognised whatever it contains. The package knows no orders
|
|
8
|
+
* and no tables: the application says what a pickup, a delivery or an
|
|
9
|
+
* incident means for it.
|
|
10
|
+
*
|
|
11
|
+
* Mount BEFORE any JSON body parser: the signature is computed on the exact
|
|
12
|
+
* bytes received (express.raw({ type: 'application/json' })).
|
|
13
|
+
*/
|
|
14
|
+
const { createHash } = require('node:crypto');
|
|
15
|
+
const { createWebhookHandler } = require('@astratra/payments');
|
|
16
|
+
|
|
17
|
+
const SIGNATURE_HEADER = 'sendcloud-signature';
|
|
18
|
+
const DEFAULT_PRUNE_OLDER_THAN_MS = 90 * 24 * 3600_000;
|
|
19
|
+
const DEFAULT_PRUNE_EVERY_MS = 24 * 3600_000;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {object} options
|
|
23
|
+
* @param {object} options.carrier a Carrier (verifySignature, readEvent)
|
|
24
|
+
* @param {object} [options.eventLog] { claim, release, record } — for example createPostgresEventLog
|
|
25
|
+
* @param {Function} [options.onEvent] (event, tools) called for every parcel status change
|
|
26
|
+
* @param {Function} [options.onPickedUp] (event, tools) first scan
|
|
27
|
+
* @param {Function} [options.onDelivered] (event, tools)
|
|
28
|
+
* @param {Function} [options.onIncident] (event, tools)
|
|
29
|
+
* @param {string} [options.signatureHeader] default 'sendcloud-signature'
|
|
30
|
+
* @param {object} [options.logger]
|
|
31
|
+
* @param {number|false} [options.pruneOlderThanMs] when the event log has prune(): handled events older
|
|
32
|
+
* than this are deleted, at most once per `pruneEveryMs`, after a webhook is answered. Default 90 days;
|
|
33
|
+
* false disables it (prune it yourself).
|
|
34
|
+
* @param {number} [options.pruneEveryMs] default 24 h
|
|
35
|
+
* @param {Function} [options.now] for tests
|
|
36
|
+
*/
|
|
37
|
+
function createCarrierWebhook(options = {}) {
|
|
38
|
+
const carrier = options.carrier;
|
|
39
|
+
if (!carrier || typeof carrier.verifySignature !== 'function' || typeof carrier.readEvent !== 'function') {
|
|
40
|
+
throw new TypeError('createCarrierWebhook needs a carrier with verifySignature() and readEvent().');
|
|
41
|
+
}
|
|
42
|
+
const header = String(options.signatureHeader || SIGNATURE_HEADER).toLowerCase();
|
|
43
|
+
const byStage = { picked_up: options.onPickedUp, delivered: options.onDelivered, incident: options.onIncident };
|
|
44
|
+
const eventLog = options.eventLog;
|
|
45
|
+
const pruneOlderThanMs = options.pruneOlderThanMs === undefined ? DEFAULT_PRUNE_OLDER_THAN_MS : options.pruneOlderThanMs;
|
|
46
|
+
const pruneEveryMs = options.pruneEveryMs || DEFAULT_PRUNE_EVERY_MS;
|
|
47
|
+
const now = options.now || Date.now;
|
|
48
|
+
const logger = options.logger || {};
|
|
49
|
+
let lastPrune = null;
|
|
50
|
+
let pruning = null;
|
|
51
|
+
|
|
52
|
+
/* The event log only grows: old handled events are deleted now and then, never on the answer's path. */
|
|
53
|
+
function maybePrune() {
|
|
54
|
+
if (!pruneOlderThanMs || !eventLog || typeof eventLog.prune !== 'function' || pruning) return null;
|
|
55
|
+
if (lastPrune !== null && now() - lastPrune < pruneEveryMs) return null;
|
|
56
|
+
lastPrune = now();
|
|
57
|
+
pruning = Promise.resolve()
|
|
58
|
+
.then(() => eventLog.prune(pruneOlderThanMs))
|
|
59
|
+
.catch((error) => { if (logger.warn) logger.warn(`[shipping] event log prune failed: ${error.message}`); })
|
|
60
|
+
.finally(() => { pruning = null; });
|
|
61
|
+
return pruning;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const handler = createWebhookHandler({
|
|
65
|
+
eventLog,
|
|
66
|
+
logger: options.logger,
|
|
67
|
+
eventId: (event) => event.id,
|
|
68
|
+
async verify({ payload, headers }) {
|
|
69
|
+
if (!Buffer.isBuffer(payload)) {
|
|
70
|
+
throw new Error('the body is not raw bytes: mount the webhook before any JSON body parser');
|
|
71
|
+
}
|
|
72
|
+
const signature = headers[header] ?? headers[header.toLowerCase()];
|
|
73
|
+
if (!(await carrier.verifySignature(payload, Array.isArray(signature) ? signature[0] : signature))) {
|
|
74
|
+
throw new Error('invalid signature');
|
|
75
|
+
}
|
|
76
|
+
let json;
|
|
77
|
+
try {
|
|
78
|
+
json = JSON.parse(payload.toString('utf8'));
|
|
79
|
+
} catch {
|
|
80
|
+
throw new Error('unreadable body');
|
|
81
|
+
}
|
|
82
|
+
const parcel = carrier.readEvent(json);
|
|
83
|
+
return {
|
|
84
|
+
id: createHash('sha256').update(payload).digest('hex'),
|
|
85
|
+
type: parcel ? 'parcel_status_changed' : String(json && json.action || 'unknown'),
|
|
86
|
+
parcel
|
|
87
|
+
};
|
|
88
|
+
},
|
|
89
|
+
events: {
|
|
90
|
+
async parcel_status_changed(event, tools) {
|
|
91
|
+
if (typeof options.onEvent === 'function') await options.onEvent(event.parcel, tools);
|
|
92
|
+
const act = byStage[event.parcel.stage];
|
|
93
|
+
if (typeof act === 'function') {
|
|
94
|
+
const outcome = await act(event.parcel, tools);
|
|
95
|
+
if (outcome) return outcome;
|
|
96
|
+
}
|
|
97
|
+
return tools.handled(event.parcel.stage || 'status');
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
async function receive(request) {
|
|
102
|
+
const answer = await handler.receive(request);
|
|
103
|
+
maybePrune();
|
|
104
|
+
return answer;
|
|
105
|
+
}
|
|
106
|
+
function middleware(req, res) {
|
|
107
|
+
return receive({ payload: req.body, headers: req.headers }).then(({ status, body }) => {
|
|
108
|
+
res.status(status).json(body);
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/** Waits for a prune in progress (tests, graceful shutdown). */
|
|
112
|
+
const settled = () => pruning || Promise.resolve();
|
|
113
|
+
return { receive, middleware, sideEffect: handler.sideEffect, settled };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
module.exports = { createCarrierWebhook, SIGNATURE_HEADER };
|