hooksend 1.0.0-test → 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/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0
4
+
5
+ - Source code now on GitHub: https://github.com/ckgiri/hooksend
6
+ - Added repository, homepage, issues and funding links.
7
+ - README screenshots now display on npm.
8
+
9
+ ## 1.0.0
10
+
11
+ First release.
12
+
13
+ - `sign()`, `generateSecret()` and `createMessageId()`: Standard Webhooks signatures (`webhook-id`, `webhook-timestamp`, `webhook-signature`), with several secrets for key rotation. Verified in tests by the official `standardwebhooks` package and by `hookseal`.
14
+ - `sendOnce()` sends one signed request with a per-attempt timeout (default 15s), never follows redirects and returns status, duration and the first 2 KB of the response.
15
+ - `deliver()` retries network errors, timeouts, 408, 429 and 5xx on a Svix-like schedule (now, 5s, 5m, 30m, 2h, 5h, 10h, 10h) with ±20% jitter, honours `Retry-After`, stops on `410 Gone` (`disabled: true`) and can be cancelled with an `AbortSignal`.
16
+ - SSRF protection on by default: only http/https, and private, loopback, link-local (including `169.254.169.254`), CGNAT, multicast and reserved addresses are refused, checked on the resolved IP used for the connection (DNS rebinding safe). `allowPrivateNetworks` and `allowHosts` for local testing. `isPrivateAddress()` is exported.
17
+ - `createDispatcher()` fans an event out to many endpoints with a shared concurrency limit, per-endpoint retries, `onDelivered` / `onFailed` / `onDisabled` callbacks, `drain()` and `close()`, and a pluggable `store` (`save`, `remove`, `due`) with `resume()` so retries can survive restarts. In memory by default.
18
+ - CLI: `hooksend secret`, `hooksend sign` and `hooksend send` (with retries, `--json` and `HOOKSEND_SECRET`).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CK Giri
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,5 +1,316 @@
1
1
  # hooksend
2
2
 
3
- Send webhooks reliably from any JavaScript runtime: Standard Webhooks signing, retries with backoff, timeouts and SSRF protection.
3
+ **Send webhooks reliably.** Signed with [Standard Webhooks](https://www.standardwebhooks.com/), retried with backoff, protected against SSRF, fanned out to many endpoints. Self-hosted, zero dependencies.
4
4
 
5
- > Placeholder release - under active development.
5
+ [![npm version](https://img.shields.io/npm/v/hooksend.svg)](https://www.npmjs.com/package/hooksend)
6
+ [![node](https://img.shields.io/node/v/hooksend.svg)](https://nodejs.org)
7
+ [![license](https://img.shields.io/npm/l/hooksend.svg)](./LICENSE)
8
+
9
+ ![hooksend: a real delivery that failed twice, retried, and was verified by hookseal](https://raw.githubusercontent.com/ckgiri/hooksend/main/assets/flow.png)
10
+
11
+ ## Quick start
12
+
13
+ ```sh
14
+ npm i hooksend
15
+ npx hooksend secret # whsec_... give this to the endpoint owner
16
+ ```
17
+
18
+ ```js
19
+ import { deliver } from "hooksend";
20
+
21
+ const endpoint = { url: "https://customer.example/webhooks", secret: process.env.WEBHOOK_SECRET };
22
+ const result = await deliver(endpoint, { type: "order.paid", data: { id: "ord_1042", total: 4999 } });
23
+
24
+ console.log(result.delivered, result.attempts.length);
25
+ ```
26
+
27
+ That's it. Every attempt is signed, failures are retried on a schedule, and private or internal addresses are refused.
28
+
29
+ ## Why
30
+
31
+ - 🧩 **Apps that offer webhooks must deliver them reliably.** That means signatures, retries, timeouts and not letting a customer point your server at your own network.
32
+ - 💸 **The popular options don't cover it.** `svix` (about 9.6M weekly downloads) is the client for Svix's paid cloud service. `standardwebhooks` (about 58M weekly) only signs and verifies. `node-webhooks` is basic and `@hookdeck/sdk` is deprecated. There was no popular self-hosted library that signs, delivers, retries and protects against SSRF.
33
+ - ✍️ **Standard Webhooks signatures.** Receivers can verify with the official `standardwebhooks` package, Svix libraries or [hookseal](https://www.npmjs.com/package/hookseal). hooksend's tests verify every request with both `standardwebhooks` and `hookseal`.
34
+ - 🔁 **Retries that behave.** Network errors, timeouts, 408, 429 and 5xx are retried with jitter; `Retry-After` is honoured; `410 Gone` tells you to drop the endpoint.
35
+ - 🛡️ **SSRF protection on by default.** SSRF is when a user registers a webhook URL like `http://169.254.169.254/` so your server fetches its own cloud credentials or internal services; hooksend refuses those addresses, checked on the IP it actually connects to.
36
+ - 📦 **Zero dependencies**, ESM and CommonJS, TypeScript types, plus a CLI for testing endpoints.
37
+
38
+ ## The webhook suite
39
+
40
+ **hooksend sends → [hookseal](https://www.npmjs.com/package/hookseal) verifies → twiceless processes once** (twiceless is coming soon).
41
+
42
+ On the receiving side, verify a hooksend webhook with hookseal:
43
+
44
+ ```js
45
+ import { verify } from "hookseal";
46
+
47
+ const result = await verify({ provider: "standard-webhooks", payload: rawBody, headers: req.headers, secret });
48
+ if (!result.valid) return res.status(401).end();
49
+ ```
50
+
51
+ ## Recipes
52
+
53
+ ### Send to one endpoint
54
+
55
+ ```js
56
+ import { deliver } from "hooksend";
57
+
58
+ const result = await deliver(
59
+ { url: "https://customer.example/webhooks", secret },
60
+ { type: "invoice.paid", data: invoice },
61
+ { onAttempt: (a) => console.log(`#${a.attempt}`, a.status ?? a.error) },
62
+ );
63
+
64
+ if (result.disabled) await removeEndpoint(); // the receiver answered 410 Gone
65
+ ```
66
+
67
+ `deliver()` never throws for delivery failures; the result tells you what happened. It resolves when the delivery succeeds or gives up, which with the default schedule can take about 27 hours, so don't await it in a request handler. Use the dispatcher or a queue instead.
68
+
69
+ ### Fan out to subscribers
70
+
71
+ ```js
72
+ import { createDispatcher } from "hooksend";
73
+
74
+ const dispatcher = createDispatcher({
75
+ concurrency: 10,
76
+ onFailed: (r) => console.warn("gave up on", r.url),
77
+ onDisabled: (r) => db.endpoints.disable(r.url),
78
+ });
79
+
80
+ // Fire and forget: every endpoint gets its own retries, a failing one never blocks the others.
81
+ dispatcher.dispatch({
82
+ type: "order.paid",
83
+ data: order,
84
+ endpoints: subscribers.map((s) => ({ url: s.url, secret: s.secret })),
85
+ });
86
+
87
+ // On shutdown
88
+ await dispatcher.close();
89
+ ```
90
+
91
+ ### Rotate secrets
92
+
93
+ Sign with the old and the new secret at the same time. The receiver accepts either, so you can switch it over without downtime.
94
+
95
+ ```js
96
+ await deliver({ url, secret: [oldSecret, newSecret] }, { type: "user.created", data: user });
97
+ // webhook-signature: v1,<old> v1,<new>
98
+ ```
99
+
100
+ ### Run in a queue or worker
101
+
102
+ If you already have a queue (BullMQ, pg-boss, SQS…), let it handle the retries and use `sendOnce()` for each try. Create the message id and timestamp once and keep them in the job, so every retry sends the same `webhook-id` and body.
103
+
104
+ ```js
105
+ import { createMessageId, sendOnce, shouldRetry } from "hooksend";
106
+
107
+ await queue.add("webhook", {
108
+ endpoint,
109
+ message: { id: createMessageId(), timestamp: new Date().toISOString(), type: "order.paid", data: order },
110
+ });
111
+
112
+ // In the worker
113
+ async function handle(job) {
114
+ const result = await sendOnce(job.data.endpoint, job.data.message, { attempt: job.attemptsMade + 1 });
115
+ if (!result.ok && shouldRetry(result)) throw new Error(result.error); // the queue retries it later
116
+ }
117
+ ```
118
+
119
+ ### Keep retries across restarts
120
+
121
+ The dispatcher keeps pending retries in memory unless you give it a `store`. Implement three methods with your database and call `resume()` on startup and on a timer:
122
+
123
+ ```js
124
+ const dispatcher = createDispatcher({
125
+ store: {
126
+ save: (job) => db.webhookJobs.upsert(job), // job includes the endpoint secret: store it like one
127
+ remove: (id) => db.webhookJobs.delete(id),
128
+ due: (now) => db.webhookJobs.findMany({ nextAttemptAt: { lte: now } }),
129
+ },
130
+ });
131
+
132
+ await dispatcher.resume();
133
+ setInterval(() => dispatcher.resume(), 60_000);
134
+ ```
135
+
136
+ ### Test locally
137
+
138
+ Private addresses are blocked by default, including `localhost`. Allow just your test receiver:
139
+
140
+ ```js
141
+ await deliver({ url: "http://localhost:3000/webhooks", secret }, event, { allowHosts: ["localhost"] });
142
+ ```
143
+
144
+ Or allow every private address with `allowPrivateNetworks: true` (never with URLs your users provide).
145
+
146
+ ## CLI
147
+
148
+ ![hooksend send output](https://raw.githubusercontent.com/ckgiri/hooksend/main/assets/cli.png)
149
+
150
+ | Command | What it does |
151
+ | --- | --- |
152
+ | `hooksend secret` | Print a new `whsec_…` signing secret |
153
+ | `hooksend sign --secret <s> --data '<body>'` | Print the three signature headers for that exact body |
154
+ | `hooksend send <url> --secret <s> --event <type> --data '<json>'` | Send a signed webhook with retries and print every attempt |
155
+
156
+ <details>
157
+ <summary><b>All CLI options</b></summary>
158
+
159
+ **`sign` options**
160
+
161
+ | Option | Default | Description |
162
+ | --- | --- | --- |
163
+ | `--secret <s>` | `HOOKSEND_SECRET` | Signing secret |
164
+ | `--data '<body>'` / `--file <path>` | required | Body to sign, exactly as given |
165
+ | `--id <msg_id>` | new `msg_…` id | Message id |
166
+ | `--timestamp <seconds>` | now | Signing time |
167
+ | `--json` | off | Print the headers as JSON |
168
+
169
+ **`send` options**
170
+
171
+ | Option | Default | Description |
172
+ | --- | --- | --- |
173
+ | `--secret <s>` | `HOOKSEND_SECRET` | Signing secret |
174
+ | `--event <type>` | required | Event type |
175
+ | `--data '<json>'` / `--file <path>` | required | Event data (JSON), sent as `{ type, timestamp, data }` |
176
+ | `--retries <n>` | `3` | Retries after the first attempt, waiting 1s, 5s, 15s, 30s, then 60s (±20%) |
177
+ | `--timeout <ms>` | `15000` | Timeout per attempt |
178
+ | `--id <msg_id>` | new `msg_…` id | Message id |
179
+ | `--allow-private` | off | Allow private, loopback and link-local targets |
180
+ | `--json` | off | Print the full result as JSON |
181
+
182
+ Exit codes: `0` delivered (or success), `1` not delivered (including blocked targets), `2` usage error.
183
+
184
+ </details>
185
+
186
+ ## API reference
187
+
188
+ <details>
189
+ <summary><b><code>deliver(endpoint, message, options?)</code></b></summary>
190
+
191
+ Sends with retries. Resolves to `{ delivered, disabled, aborted, id, attempts }`.
192
+
193
+ `endpoint`: `{ url, secret, headers? }`. `secret` can be an array to sign with several secrets.
194
+
195
+ `message`: `{ type, data, id?, timestamp? }` (timestamp as `Date`, ISO string or epoch ms) is sent as JSON `{ "type", "timestamp" (ISO), "data" }`. Pass `{ body, id? }` instead to send an exact string or bytes.
196
+
197
+ | Option | Default | Description |
198
+ | --- | --- | --- |
199
+ | `schedule` | `DEFAULT_SCHEDULE` | Wait in ms before each attempt; its length is the maximum number of attempts |
200
+ | `jitter` | `0.2` | Random spread on each wait (±20%) |
201
+ | `retryOn` | `shouldRetry` | `(attempt) => boolean`, decides whether a failure is retried |
202
+ | `maxRetryAfterMs` | `3600000` | Cap for `Retry-After` waits (1 hour) |
203
+ | `timeoutMs` | `15000` | Timeout per attempt |
204
+ | `headers` | none | Extra request headers |
205
+ | `allowPrivateNetworks` | `false` | Allow private, loopback and link-local targets |
206
+ | `allowHosts` | `[]` | Hostnames or IPs that skip the private-address check |
207
+ | `signal` | none | `AbortSignal` that cancels the wait between attempts and the request in flight |
208
+ | `onAttempt` | none | Called after every attempt |
209
+ | `startAttempt` | `1` | Resume at this attempt number (sent right away) |
210
+ | `sleep`, `random`, `now`, `resolver` | built-in | Inject a wait function, random source, clock or DNS resolver (for tests) |
211
+
212
+ </details>
213
+
214
+ <details>
215
+ <summary><b><code>sendOnce(endpoint, message, options?)</code></b></summary>
216
+
217
+ One signed attempt, never throws for network or HTTP failures. Takes `timeoutMs`, `headers`, `allowPrivateNetworks`, `allowHosts`, `signal` and `attempt` (the number to report). Resolves to an attempt result:
218
+
219
+ | Field | Description |
220
+ | --- | --- |
221
+ | `ok` | `true` for a 2xx response |
222
+ | `status`, `statusText` | HTTP status, or `null` without a response |
223
+ | `durationMs` | Time until the response (or the error) |
224
+ | `attempt` | Attempt number |
225
+ | `url`, `id` | Target URL and message id |
226
+ | `error` | `"HTTP 503 Service Unavailable"`, `"Timed out after 15000ms"`, `"Redirect not followed (302 to …)"`, `"Blocked: …"`, a network error… |
227
+ | `errorType` | `"timeout"`, `"network"`, `"blocked"`, `"aborted"` or `"invalid"` when there was no usable response |
228
+ | `responseBody` | First 2 KB of the response |
229
+ | `retryAfterMs` | Parsed `Retry-After` header |
230
+ | `retryInMs` | Set by `deliver()` when another attempt follows |
231
+
232
+ Headers sent: `webhook-id`, `webhook-timestamp`, `webhook-signature`, `content-type: application/json`, `user-agent: hooksend/<version>`, plus your own. The signature headers can't be overridden.
233
+
234
+ </details>
235
+
236
+ <details>
237
+ <summary><b><code>createDispatcher(options?)</code></b></summary>
238
+
239
+ Takes the same options as `deliver()` (except `signal` and `startAttempt`), plus:
240
+
241
+ | Option | Default | Description |
242
+ | --- | --- | --- |
243
+ | `concurrency` | `10` | Maximum HTTP requests in flight (waits between retries don't count) |
244
+ | `store` | `new MemoryStore()` | Where pending jobs live: `{ save(job), remove(id), due(now) }` |
245
+ | `onAttempt` | none | Called after every attempt to any endpoint |
246
+ | `onDelivered`, `onFailed`, `onDisabled` | none | Called once per endpoint with its final result |
247
+
248
+ | Method | Description |
249
+ | --- | --- |
250
+ | `dispatch({ type, data, id?, endpoints })` | Delivers to every endpoint in parallel. Resolves to `{ id, results }` (one result per endpoint, with `url` and `jobId`) once all are finished |
251
+ | `resume()` | Runs the store's due jobs |
252
+ | `drain()` | Resolves when every delivery in progress has finished, including retries |
253
+ | `close()` | Stops accepting work, cancels waits between retries (jobs stay in the store) and waits for requests in flight |
254
+ | `pending` | Number of endpoint deliveries in progress |
255
+
256
+ A stored job is `{ id, messageId, type, body, endpoint, attempt, nextAttemptAt, createdAt }`. It is saved before the first attempt and after each failed attempt, and removed once delivered, given up or disabled.
257
+
258
+ </details>
259
+
260
+ <details>
261
+ <summary><b>Signing: <code>sign</code>, <code>generateSecret</code>, <code>createMessageId</code></b></summary>
262
+
263
+ - `generateSecret()` returns `"whsec_"` + base64 of 32 random bytes.
264
+ - `createMessageId()` returns `"msg_"` + 24 random letters and digits.
265
+ - `sign({ id?, timestamp?, body, secret | secrets })` returns `{ "webhook-id", "webhook-timestamp", "webhook-signature" }`. The signature is `v1,` + base64 HMAC-SHA256 of `id.timestamp.body`, with the secret decoded from base64 after the optional `whsec_` prefix. Several secrets give several space-separated signatures. `timestamp` is a `Date` or epoch seconds (default now).
266
+ - `decodeSecret(secret)` returns the key bytes, or throws for an invalid secret.
267
+
268
+ </details>
269
+
270
+ <details>
271
+ <summary><b>SSRF and retry helpers</b></summary>
272
+
273
+ - `isPrivateAddress(ip)` is `true` for any address that isn't public unicast (see the rules below). Invalid input also returns `true`.
274
+ - `shouldRetry(attempt)` is the default `retryOn`.
275
+ - `applyJitter(ms, jitter?, random?)`, `parseRetryAfter(value, now?)`, `checkUrl(url, policy?)` and `createSafeLookup(policy?)` are the building blocks `deliver()` uses.
276
+ - Constants: `DEFAULT_SCHEDULE`, `DEFAULT_JITTER`, `DEFAULT_MAX_RETRY_AFTER_MS`, `DEFAULT_TIMEOUT_MS`, `VERSION`.
277
+
278
+ </details>
279
+
280
+ ## Good to know
281
+
282
+ **Default retry schedule** (eight attempts over about 27.5 hours, each wait ±20%):
283
+
284
+ | Attempt | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
285
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- |
286
+ | Wait before it | now | 5s | 5m | 30m | 2h | 5h | 10h | 10h |
287
+
288
+ **What is retried**
289
+
290
+ | Outcome | Retried? |
291
+ | --- | --- |
292
+ | 2xx | Delivered |
293
+ | Network error, timeout | Yes |
294
+ | 408, 429, 5xx | Yes. `Retry-After` (seconds or HTTP date) is honoured: the next wait is the longer of the schedule and `Retry-After`, capped at `maxRetryAfterMs` |
295
+ | `410 Gone` | No. Stops with `disabled: true`: remove the endpoint |
296
+ | 3xx | No. Redirects are never followed |
297
+ | Other 4xx | No |
298
+ | Blocked or invalid URL | No |
299
+
300
+ Every attempt is signed again with a fresh `webhook-timestamp` (so receivers' 5-minute replay window still passes on late retries) and the same `webhook-id` and body (so receivers can de-duplicate).
301
+
302
+ **SSRF rules** (unless `allowPrivateNetworks` or `allowHosts`)
303
+
304
+ - Only `http:` and `https:` URLs.
305
+ - Refused: `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10` (CGNAT), `127.0.0.0/8`, `169.254.0.0/16` (link-local and cloud metadata `169.254.169.254`), `172.16.0.0/12`, `192.168.0.0/16`, documentation and benchmark ranges, multicast and reserved `224.0.0.0` and up; IPv6 `::`, `::1`, `fc00::/7`, `fe80::/10`, `fec0::/10`, `ff00::/8`, `2001:db8::/32`, and IPv4 addresses embedded in IPv6 (`::ffff:127.0.0.1`, NAT64, 6to4) are checked as IPv4.
306
+ - Hostnames are checked when the connection is made: every address DNS returns must be public, and the request connects to one of those checked addresses. A hostname that resolves to a public IP when the user registers it and a private one later (DNS rebinding) is still refused.
307
+ - Requests use `node:http` / `node:https` without connection reuse, so every request runs the check.
308
+
309
+ **Pending retries are in memory by default.** If the process exits, retries that were waiting are lost. Pass a `store` and call `resume()` to keep them (see [Keep retries across restarts](#keep-retries-across-restarts)).
310
+
311
+ - **Zero runtime dependencies.** Node 20+ (uses `node:http`, `node:https`, `node:dns` and `node:crypto`), so it doesn't run in browsers or edge runtimes.
312
+ - Works with ESM and CommonJS, with TypeScript types.
313
+
314
+ ## License
315
+
316
+ MIT © CK Giri