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/dist/cli.cjs ADDED
@@ -0,0 +1,766 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/run.ts
27
+ var import_promises = require("fs/promises");
28
+
29
+ // src/send.ts
30
+ var import_node_http = __toESM(require("http"), 1);
31
+ var import_node_https = __toESM(require("https"), 1);
32
+
33
+ // src/sign.ts
34
+ var import_node_crypto = require("crypto");
35
+ var SECRET_PREFIX = "whsec_";
36
+ var BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
37
+ function generateSecret() {
38
+ return SECRET_PREFIX + (0, import_node_crypto.randomBytes)(32).toString("base64");
39
+ }
40
+ var ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
41
+ function createMessageId() {
42
+ let id = "msg_";
43
+ while (id.length < 28) {
44
+ for (const byte of (0, import_node_crypto.randomBytes)(32)) {
45
+ if (byte < 248 && id.length < 28) id += ALPHABET[byte % 62];
46
+ }
47
+ }
48
+ return id;
49
+ }
50
+ function decodeSecret(secret) {
51
+ if (typeof secret !== "string") throw new TypeError("Secret must be a string");
52
+ const raw = secret.startsWith(SECRET_PREFIX) ? secret.slice(SECRET_PREFIX.length) : secret;
53
+ if (raw.length === 0 || !BASE64.test(raw)) {
54
+ throw new TypeError('Invalid secret: expected "whsec_" followed by base64 (use generateSecret())');
55
+ }
56
+ return Buffer.from(raw, "base64");
57
+ }
58
+ function toSeconds(timestamp) {
59
+ if (timestamp === void 0) return Math.floor(Date.now() / 1e3);
60
+ if (timestamp instanceof Date) return Math.floor(timestamp.getTime() / 1e3);
61
+ if (!Number.isFinite(timestamp)) throw new TypeError("Invalid timestamp");
62
+ return Math.floor(timestamp);
63
+ }
64
+ function secretList(options) {
65
+ const list = [];
66
+ if (Array.isArray(options.secret)) list.push(...options.secret);
67
+ else if (options.secret !== void 0) list.push(options.secret);
68
+ if (options.secrets) list.push(...options.secrets);
69
+ if (list.length === 0) throw new TypeError("A secret is required to sign a webhook");
70
+ return list;
71
+ }
72
+ function sign(options) {
73
+ const id = options.id ?? createMessageId();
74
+ if (typeof id !== "string" || id.length === 0) throw new TypeError("Message id must be a non-empty string");
75
+ const timestamp = toSeconds(options.timestamp);
76
+ const body = typeof options.body === "string" ? Buffer.from(options.body, "utf8") : options.body;
77
+ if (!(body instanceof Uint8Array)) throw new TypeError("Body must be a string or Uint8Array");
78
+ const keys = secretList(options).map(decodeSecret);
79
+ const prefix = Buffer.from(`${id}.${timestamp}.`, "utf8");
80
+ const signatures = keys.map(
81
+ (key) => "v1," + (0, import_node_crypto.createHmac)("sha256", key).update(prefix).update(body).digest("base64")
82
+ );
83
+ return {
84
+ "webhook-id": id,
85
+ "webhook-timestamp": String(timestamp),
86
+ "webhook-signature": signatures.join(" ")
87
+ };
88
+ }
89
+
90
+ // src/ssrf.ts
91
+ var import_node_dns = require("dns");
92
+ var import_node_net = require("net");
93
+ var BlockedError = class extends Error {
94
+ code = "HOOKSEND_BLOCKED";
95
+ constructor(message) {
96
+ super(message);
97
+ this.name = "BlockedError";
98
+ }
99
+ };
100
+ function parseIPv4(ip) {
101
+ const parts = ip.split(".");
102
+ if (parts.length !== 4) return null;
103
+ const out = [];
104
+ for (const part of parts) {
105
+ if (!/^\d{1,3}$/.test(part)) return null;
106
+ const n = Number(part);
107
+ if (n > 255) return null;
108
+ out.push(n);
109
+ }
110
+ return out;
111
+ }
112
+ function ipv4Private(b) {
113
+ const [a, c] = [b[0], b[1]];
114
+ const d = b[2];
115
+ return a === 0 || // "this" network
116
+ a === 10 || // private
117
+ a === 100 && c >= 64 && c <= 127 || // CGNAT 100.64/10
118
+ a === 127 || // loopback
119
+ a === 169 && c === 254 || // link-local, cloud metadata
120
+ a === 172 && c >= 16 && c <= 31 || // private
121
+ a === 192 && c === 0 && d === 0 || // IETF protocol assignments
122
+ a === 192 && c === 0 && d === 2 || // TEST-NET-1
123
+ a === 192 && c === 88 && d === 99 || // 6to4 relay anycast
124
+ a === 192 && c === 168 || // private
125
+ a === 198 && (c === 18 || c === 19) || // benchmarking
126
+ a === 198 && c === 51 && d === 100 || // TEST-NET-2
127
+ a === 203 && c === 0 && d === 113 || // TEST-NET-3
128
+ a >= 224;
129
+ }
130
+ function parseIPv6(input) {
131
+ let ip = input;
132
+ const zone = ip.indexOf("%");
133
+ if (zone !== -1) ip = ip.slice(0, zone);
134
+ if ((0, import_node_net.isIP)(ip) !== 6) return null;
135
+ const lastColon = ip.lastIndexOf(":");
136
+ const tail = ip.slice(lastColon + 1);
137
+ if (tail.includes(".")) {
138
+ const v4 = parseIPv4(tail);
139
+ if (!v4) return null;
140
+ ip = `${ip.slice(0, lastColon + 1)}${(v4[0] << 8 | v4[1]).toString(16)}:${(v4[2] << 8 | v4[3]).toString(16)}`;
141
+ }
142
+ const [head, rest] = ip.split("::");
143
+ const headParts = head ? head.split(":") : [];
144
+ const restParts = rest !== void 0 && rest !== "" ? rest.split(":") : [];
145
+ const fill = rest !== void 0 ? 8 - headParts.length - restParts.length : 0;
146
+ const hextets = [...headParts, ...Array(Math.max(fill, 0)).fill("0"), ...restParts].map(
147
+ (h) => parseInt(h, 16)
148
+ );
149
+ if (hextets.length !== 8 || hextets.some((h) => Number.isNaN(h))) return null;
150
+ return hextets;
151
+ }
152
+ function embeddedV4(h, from) {
153
+ return [h[from] >> 8, h[from] & 255, h[from + 1] >> 8, h[from + 1] & 255];
154
+ }
155
+ function ipv6Private(h) {
156
+ const zeroUntil = (n) => h.slice(0, n).every((x) => x === 0);
157
+ if (zeroUntil(8)) return true;
158
+ if (zeroUntil(7) && h[7] === 1) return true;
159
+ if (zeroUntil(5) && h[5] === 65535) return ipv4Private(embeddedV4(h, 6));
160
+ if (zeroUntil(6)) return true;
161
+ if (zeroUntil(4) && h[4] === 65535 && h[5] === 0) return true;
162
+ if (h[0] === 100 && h[1] === 65435 && h.slice(2, 6).every((x) => x === 0)) {
163
+ return ipv4Private(embeddedV4(h, 6));
164
+ }
165
+ if (h[0] === 8194) return ipv4Private(embeddedV4(h, 1));
166
+ const first = h[0];
167
+ return (first & 65024) === 64512 || // unique local fc00::/7
168
+ (first & 65472) === 65152 || // link-local fe80::/10
169
+ (first & 65472) === 65216 || // site-local fec0::/10 (deprecated)
170
+ (first & 65280) === 65280 || // multicast ff00::/8
171
+ first === 8193 && h[1] === 3512 || // documentation 2001:db8::/32
172
+ first === 256 && h[1] === 0 && h[2] === 0 && h[3] === 0;
173
+ }
174
+ function isPrivateAddress(ip) {
175
+ const raw = ip.startsWith("[") && ip.endsWith("]") ? ip.slice(1, -1) : ip;
176
+ const v4 = parseIPv4(raw);
177
+ if (v4) return ipv4Private(v4);
178
+ const v6 = parseIPv6(raw);
179
+ if (v6) return ipv6Private(v6);
180
+ return true;
181
+ }
182
+ function bareHost(hostname) {
183
+ const h = hostname.toLowerCase();
184
+ return h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
185
+ }
186
+ function allowSet(policy) {
187
+ return new Set((policy.allowHosts ?? []).map(bareHost));
188
+ }
189
+ function checkUrl(url, policy = {}) {
190
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
191
+ throw new BlockedError(`Blocked: only http: and https: URLs are allowed (got ${url.protocol})`);
192
+ }
193
+ if (policy.allowPrivateNetworks) return;
194
+ const host = bareHost(url.hostname);
195
+ if (allowSet(policy).has(host)) return;
196
+ if ((0, import_node_net.isIP)(host) !== 0 && isPrivateAddress(host)) {
197
+ throw new BlockedError(`Blocked: ${url.hostname} is a private address${host === url.hostname ? "" : ` (${host})`}`);
198
+ }
199
+ }
200
+ var defaultResolver = (hostname) => new Promise((resolve, reject) => {
201
+ (0, import_node_dns.lookup)(hostname, { all: true, family: 0 }, (err, addresses) => {
202
+ if (err) reject(err);
203
+ else resolve(addresses);
204
+ });
205
+ });
206
+ function createSafeLookup(policy = {}) {
207
+ const resolver = policy.resolver ?? defaultResolver;
208
+ const allowed = allowSet(policy);
209
+ return (hostname, options, callback) => {
210
+ const opts = typeof options === "object" && options !== null ? options : {};
211
+ const family = opts.family === 4 || opts.family === "IPv4" ? 4 : opts.family === 6 || opts.family === "IPv6" ? 6 : 0;
212
+ resolver(hostname).then(
213
+ (all) => {
214
+ const addresses = family === 0 ? all : all.filter((a) => a.family === family);
215
+ if (addresses.length === 0) {
216
+ const err = new Error(`getaddrinfo ENOTFOUND ${hostname}`);
217
+ err.code = "ENOTFOUND";
218
+ callback(err, "");
219
+ return;
220
+ }
221
+ const skip = policy.allowPrivateNetworks || allowed.has(bareHost(hostname));
222
+ if (!skip) {
223
+ for (const a of addresses) {
224
+ if (isPrivateAddress(a.address) && !allowed.has(bareHost(a.address))) {
225
+ callback(new BlockedError(`Blocked: ${hostname} resolves to a private address (${a.address})`), "");
226
+ return;
227
+ }
228
+ }
229
+ }
230
+ if (opts.all) callback(null, addresses);
231
+ else callback(null, addresses[0].address, addresses[0].family);
232
+ },
233
+ (err) => callback(err, "")
234
+ );
235
+ };
236
+ }
237
+
238
+ // src/version.ts
239
+ var VERSION = true ? "1.1.0" : "dev";
240
+
241
+ // src/send.ts
242
+ var MAX_RESPONSE_BYTES = 2048;
243
+ var DEFAULT_TIMEOUT_MS = 15e3;
244
+ function prepareMessage(message, now = Date.now) {
245
+ const id = message.id ?? createMessageId();
246
+ if (message.body !== void 0) {
247
+ const body = typeof message.body === "string" ? Buffer.from(message.body, "utf8") : message.body;
248
+ return { id, body };
249
+ }
250
+ if (typeof message.type !== "string" || message.type.length === 0) {
251
+ throw new TypeError("Message needs a `type` (or a raw `body`)");
252
+ }
253
+ const date = message.timestamp === void 0 ? new Date(now()) : new Date(message.timestamp);
254
+ if (Number.isNaN(date.getTime())) throw new TypeError("Invalid message timestamp");
255
+ const timestamp = date.toISOString();
256
+ const json = JSON.stringify({ type: message.type, timestamp, data: message.data ?? null });
257
+ return { id, body: Buffer.from(json, "utf8") };
258
+ }
259
+ function parseRetryAfter(value, now = Date.now()) {
260
+ if (value === void 0) return void 0;
261
+ const v = value.trim();
262
+ if (v === "") return void 0;
263
+ if (/^\d+(\.\d+)?$/.test(v)) return Math.round(Number(v) * 1e3);
264
+ const date = Date.parse(v);
265
+ if (Number.isNaN(date)) return void 0;
266
+ return Math.max(0, date - now);
267
+ }
268
+ function describeError(err) {
269
+ if (err instanceof BlockedError) return { message: err.message, type: "blocked" };
270
+ if (err instanceof AggregateError) {
271
+ const blocked = err.errors.find((e) => e instanceof BlockedError);
272
+ if (blocked) return { message: blocked.message, type: "blocked" };
273
+ const first = err.errors[0];
274
+ if (first) return describeError(first);
275
+ }
276
+ if (err instanceof Error) {
277
+ const code = err.code;
278
+ return { message: err.message || code || "Network error", type: "network" };
279
+ }
280
+ return { message: String(err), type: "network" };
281
+ }
282
+ function lowerHeaders(headers) {
283
+ const out = {};
284
+ if (headers) for (const [k, v] of Object.entries(headers)) out[k.toLowerCase()] = String(v);
285
+ return out;
286
+ }
287
+ async function sendOnce(endpoint, message, options = {}) {
288
+ const now = options.now ?? Date.now;
289
+ const attempt = options.attempt ?? 1;
290
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
291
+ const prepared = "body" in message && message.body instanceof Uint8Array && typeof message.id === "string" ? message : prepareMessage(message, now);
292
+ const started = performance.now();
293
+ const base = { attempt, url: endpoint.url, id: prepared.id };
294
+ const fail = (error, errorType) => ({
295
+ ...base,
296
+ ok: false,
297
+ status: null,
298
+ durationMs: Math.round(performance.now() - started),
299
+ error,
300
+ errorType
301
+ });
302
+ let url;
303
+ try {
304
+ url = new URL(endpoint.url);
305
+ } catch {
306
+ return fail(`Invalid URL: ${endpoint.url}`, "invalid");
307
+ }
308
+ try {
309
+ checkUrl(url, options);
310
+ } catch (err) {
311
+ return fail(err.message, "blocked");
312
+ }
313
+ if (options.signal?.aborted) return fail("Aborted", "aborted");
314
+ const signature = sign({
315
+ id: prepared.id,
316
+ timestamp: Math.floor(now() / 1e3),
317
+ body: prepared.body,
318
+ secret: endpoint.secret
319
+ });
320
+ const headers = {
321
+ "content-type": "application/json",
322
+ "user-agent": `hooksend/${VERSION}`,
323
+ ...lowerHeaders(options.headers),
324
+ ...lowerHeaders(endpoint.headers),
325
+ ...signature,
326
+ "content-length": String(prepared.body.byteLength)
327
+ };
328
+ const mod = url.protocol === "https:" ? import_node_https.default : import_node_http.default;
329
+ return new Promise((resolve) => {
330
+ let settled = false;
331
+ const finish = (result) => {
332
+ if (settled) return;
333
+ settled = true;
334
+ clearTimeout(timer);
335
+ options.signal?.removeEventListener("abort", onAbort);
336
+ resolve(result);
337
+ };
338
+ let failure;
339
+ const req = mod.request(url, {
340
+ method: "POST",
341
+ headers,
342
+ agent: false,
343
+ lookup: createSafeLookup(options)
344
+ });
345
+ const timer = setTimeout(() => {
346
+ failure = { message: `Timed out after ${timeoutMs}ms`, type: "timeout" };
347
+ req.destroy(new Error(failure.message));
348
+ }, timeoutMs);
349
+ const onAbort = () => {
350
+ failure = { message: "Aborted", type: "aborted" };
351
+ req.destroy(new Error("Aborted"));
352
+ };
353
+ options.signal?.addEventListener("abort", onAbort, { once: true });
354
+ req.on("error", (err) => {
355
+ const info = failure ?? describeError(err);
356
+ finish(fail(info.message, info.type));
357
+ });
358
+ req.on("response", (res) => {
359
+ const status = res.statusCode ?? 0;
360
+ const durationMs = Math.round(performance.now() - started);
361
+ const chunks = [];
362
+ let size = 0;
363
+ const done = () => {
364
+ const responseBody = Buffer.concat(chunks).subarray(0, MAX_RESPONSE_BYTES).toString("utf8");
365
+ const retryAfter = res.headers["retry-after"];
366
+ const retryAfterMs = parseRetryAfter(Array.isArray(retryAfter) ? retryAfter[0] : retryAfter, now());
367
+ const ok = status >= 200 && status < 300;
368
+ let error;
369
+ if (!ok) {
370
+ error = status >= 300 && status < 400 ? `Redirect not followed (${status}${res.headers.location ? ` to ${res.headers.location}` : ""})` : `HTTP ${status}${res.statusMessage ? ` ${res.statusMessage}` : ""}`;
371
+ }
372
+ finish({
373
+ ...base,
374
+ ok,
375
+ status,
376
+ ...res.statusMessage ? { statusText: res.statusMessage } : {},
377
+ durationMs,
378
+ ...error !== void 0 ? { error } : {},
379
+ ...responseBody !== "" ? { responseBody } : {},
380
+ ...retryAfterMs !== void 0 ? { retryAfterMs } : {}
381
+ });
382
+ res.destroy();
383
+ };
384
+ res.on("data", (chunk) => {
385
+ if (size >= MAX_RESPONSE_BYTES) return;
386
+ chunks.push(chunk);
387
+ size += chunk.length;
388
+ if (size >= MAX_RESPONSE_BYTES) done();
389
+ });
390
+ res.on("end", done);
391
+ res.on("error", done);
392
+ res.on("close", done);
393
+ });
394
+ req.end(prepared.body);
395
+ });
396
+ }
397
+
398
+ // src/deliver.ts
399
+ var SECOND = 1e3;
400
+ var MINUTE = 60 * SECOND;
401
+ var HOUR = 60 * MINUTE;
402
+ var DEFAULT_SCHEDULE = Object.freeze([
403
+ 0,
404
+ 5 * SECOND,
405
+ 5 * MINUTE,
406
+ 30 * MINUTE,
407
+ 2 * HOUR,
408
+ 5 * HOUR,
409
+ 10 * HOUR,
410
+ 10 * HOUR
411
+ ]);
412
+ var DEFAULT_JITTER = 0.2;
413
+ var DEFAULT_MAX_RETRY_AFTER_MS = HOUR;
414
+ function shouldRetry(result) {
415
+ if (result.ok) return false;
416
+ if (result.status === null) return result.errorType === "network" || result.errorType === "timeout";
417
+ return result.status === 408 || result.status === 429 || result.status >= 500;
418
+ }
419
+ var defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
420
+ if (signal?.aborted) {
421
+ reject(new Error("Aborted"));
422
+ return;
423
+ }
424
+ const timer = setTimeout(() => {
425
+ signal?.removeEventListener("abort", onAbort);
426
+ resolve();
427
+ }, ms);
428
+ const onAbort = () => {
429
+ clearTimeout(timer);
430
+ reject(new Error("Aborted"));
431
+ };
432
+ signal?.addEventListener("abort", onAbort, { once: true });
433
+ });
434
+ function applyJitter(ms, jitter = DEFAULT_JITTER, random = Math.random) {
435
+ if (ms <= 0 || jitter <= 0) return Math.max(0, ms);
436
+ return Math.max(0, Math.round(ms * (1 + (random() * 2 - 1) * jitter)));
437
+ }
438
+ function safeCall(fn, arg) {
439
+ if (!fn) return;
440
+ try {
441
+ fn(arg);
442
+ } catch {
443
+ }
444
+ }
445
+ async function deliverWith(endpoint, message, options = {}, hooks = {}) {
446
+ const now = options.now ?? Date.now;
447
+ const schedule = options.schedule ?? DEFAULT_SCHEDULE;
448
+ if (schedule.length === 0 || schedule.some((ms) => !Number.isFinite(ms) || ms < 0)) {
449
+ throw new TypeError("schedule must be a non-empty array of waits in ms (>= 0)");
450
+ }
451
+ const jitter = options.jitter ?? DEFAULT_JITTER;
452
+ const random = options.random ?? Math.random;
453
+ const sleep = options.sleep ?? defaultSleep;
454
+ const retryOn = options.retryOn ?? shouldRetry;
455
+ const maxRetryAfter = options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS;
456
+ const limit = hooks.limit ?? ((fn) => fn());
457
+ const start = Math.max(1, Math.floor(options.startAttempt ?? 1));
458
+ const prepared = "body" in message && message.body instanceof Uint8Array && typeof message.id === "string" ? message : prepareMessage(message, now);
459
+ const attempts = [];
460
+ const result = (extra = {}) => ({
461
+ delivered: false,
462
+ disabled: false,
463
+ aborted: false,
464
+ id: prepared.id,
465
+ attempts,
466
+ ...extra
467
+ });
468
+ let wait = start === 1 ? applyJitter(schedule[0], jitter, random) : 0;
469
+ for (let attempt = start; attempt <= schedule.length; attempt++) {
470
+ if (wait > 0) {
471
+ try {
472
+ await sleep(wait, hooks.waitSignal ?? options.signal);
473
+ } catch {
474
+ return result({ aborted: true });
475
+ }
476
+ }
477
+ if (options.signal?.aborted || hooks.waitSignal?.aborted) return result({ aborted: true });
478
+ const sendOptions = { ...options, attempt };
479
+ const res = await limit(() => sendOnce(endpoint, prepared, sendOptions));
480
+ attempts.push(res);
481
+ if (res.ok) {
482
+ safeCall(options.onAttempt, res);
483
+ return result({ delivered: true });
484
+ }
485
+ if (res.status === 410) {
486
+ safeCall(options.onAttempt, res);
487
+ return result({ disabled: true });
488
+ }
489
+ if (res.errorType === "aborted") {
490
+ safeCall(options.onAttempt, res);
491
+ return result({ aborted: true });
492
+ }
493
+ const retry = attempt < schedule.length && retryOn(res);
494
+ if (!retry) {
495
+ safeCall(options.onAttempt, res);
496
+ return result();
497
+ }
498
+ wait = applyJitter(schedule[attempt], jitter, random);
499
+ if (res.retryAfterMs !== void 0) wait = Math.max(wait, Math.min(res.retryAfterMs, maxRetryAfter));
500
+ res.retryInMs = wait;
501
+ safeCall(options.onAttempt, res);
502
+ if (hooks.onRetryScheduled) await hooks.onRetryScheduled(attempt + 1, wait);
503
+ }
504
+ return result();
505
+ }
506
+ function deliver(endpoint, message, options = {}) {
507
+ return deliverWith(endpoint, message, options);
508
+ }
509
+
510
+ // src/run.ts
511
+ var defaultIO = {
512
+ stdout: (text) => process.stdout.write(text),
513
+ stderr: (text) => process.stderr.write(text)
514
+ };
515
+ var HELP = `hooksend ${VERSION} - send webhooks reliably
516
+
517
+ Usage:
518
+ hooksend secret
519
+ Prints a new signing secret (whsec_...).
520
+
521
+ hooksend sign --secret <secret> (--data '<body>' | --file <path>) [--id <msg_id>] [--timestamp <seconds>] [--json]
522
+ Prints the Standard Webhooks headers for that exact body.
523
+
524
+ hooksend send <url> --secret <secret> --event <type> (--data '<json>' | --file <payload.json>) [options]
525
+ Sends a signed webhook { type, timestamp, data } with retries and prints every attempt.
526
+ --retries <n> Retries after the first attempt (default: 3; waits 1s, 5s, 15s, 30s, 60s...)
527
+ --timeout <ms> Timeout per attempt (default: 15000)
528
+ --id <msg_id> Message id (default: a new msg_... id)
529
+ --allow-private Allow private, loopback and link-local targets (local testing)
530
+ --json Print the result as JSON
531
+
532
+ The secret can also come from the HOOKSEND_SECRET environment variable.
533
+
534
+ hooksend --help | --version
535
+
536
+ Exit codes: 0 delivered (or success), 1 not delivered, 2 usage error.
537
+ `;
538
+ var UsageError = class extends Error {
539
+ };
540
+ function parseArgs(args, spec) {
541
+ const positionals = [];
542
+ const flags = {};
543
+ for (let i = 0; i < args.length; i++) {
544
+ const arg = args[i];
545
+ if (arg === "--") {
546
+ positionals.push(...args.slice(i + 1));
547
+ break;
548
+ }
549
+ if (!arg.startsWith("--") || arg === "-") {
550
+ positionals.push(arg);
551
+ continue;
552
+ }
553
+ const eq = arg.indexOf("=");
554
+ const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
555
+ const kind = spec[name];
556
+ if (!kind) throw new UsageError(`Unknown option --${name}`);
557
+ if (kind === "boolean") {
558
+ if (eq !== -1) throw new UsageError(`Option --${name} does not take a value`);
559
+ flags[name] = true;
560
+ continue;
561
+ }
562
+ let value;
563
+ if (eq !== -1) value = arg.slice(eq + 1);
564
+ else {
565
+ value = args[i + 1];
566
+ if (value === void 0 || value.startsWith("--") && value.length > 2) {
567
+ throw new UsageError(`Option --${name} needs a value`);
568
+ }
569
+ i++;
570
+ }
571
+ flags[name] = value;
572
+ }
573
+ return { positionals, flags };
574
+ }
575
+ function str(flags, name) {
576
+ const v = flags[name];
577
+ return typeof v === "string" ? v : void 0;
578
+ }
579
+ function noPositionals(parsed) {
580
+ if (parsed.positionals.length > 0) throw new UsageError(`Unexpected argument "${parsed.positionals[0]}"`);
581
+ }
582
+ function intFlag(flags, name, fallback, min) {
583
+ const raw = str(flags, name);
584
+ if (raw === void 0) return fallback;
585
+ if (!/^\d+$/.test(raw) || Number(raw) < min) throw new UsageError(`--${name} must be a whole number >= ${min}`);
586
+ return Number(raw);
587
+ }
588
+ function secretFrom(parsed, io) {
589
+ const secret = str(parsed.flags, "secret") ?? (io.env ?? process.env).HOOKSEND_SECRET;
590
+ if (!secret) throw new UsageError("Missing --secret (or set HOOKSEND_SECRET)");
591
+ return secret;
592
+ }
593
+ async function bodyFrom(parsed) {
594
+ const data = str(parsed.flags, "data");
595
+ const file = str(parsed.flags, "file");
596
+ if (data !== void 0 && file !== void 0) throw new UsageError("Use --data or --file, not both");
597
+ if (data !== void 0) return data;
598
+ if (file !== void 0) {
599
+ try {
600
+ return await (0, import_promises.readFile)(file, "utf8");
601
+ } catch {
602
+ throw new UsageError(`Cannot read --file ${file}`);
603
+ }
604
+ }
605
+ throw new UsageError("Missing --data or --file");
606
+ }
607
+ function cliSchedule(retries) {
608
+ const waits = [1e3, 5e3, 15e3, 3e4, 6e4];
609
+ return [0, ...Array.from({ length: retries }, (_, i) => waits[Math.min(i, waits.length - 1)])];
610
+ }
611
+ function formatDuration(ms) {
612
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
613
+ if (ms < 6e4) return `${(ms / 1e3).toFixed(1)}s`;
614
+ if (ms < 36e5) return `${Math.round(ms / 6e4)}m`;
615
+ return `${(ms / 36e5).toFixed(1)}h`;
616
+ }
617
+ function formatAttempt(r) {
618
+ const outcome = r.status !== null ? r.status >= 300 && r.status < 400 ? r.error ?? `${r.status}` : `${r.status}${r.statusText ? ` ${r.statusText}` : ""}` : r.error ?? "failed";
619
+ const mark = r.ok ? "\u2714" : "\u2716";
620
+ const retry = r.retryInMs !== void 0 ? ` retrying in ${formatDuration(r.retryInMs)}` : "";
621
+ return ` ${mark} #${r.attempt} ${outcome} ${r.durationMs}ms${retry}
622
+ `;
623
+ }
624
+ function cmdSecret(args, io) {
625
+ noPositionals(parseArgs(args, {}));
626
+ io.stdout(`${generateSecret()}
627
+ `);
628
+ return 0;
629
+ }
630
+ async function cmdSign(args, io) {
631
+ const parsed = parseArgs(args, {
632
+ secret: "string",
633
+ data: "string",
634
+ file: "string",
635
+ id: "string",
636
+ timestamp: "string",
637
+ json: "boolean"
638
+ });
639
+ noPositionals(parsed);
640
+ const secret = secretFrom(parsed, io);
641
+ const body = await bodyFrom(parsed);
642
+ const ts = str(parsed.flags, "timestamp");
643
+ if (ts !== void 0 && !/^\d+$/.test(ts)) throw new UsageError("--timestamp must be epoch seconds");
644
+ const id = str(parsed.flags, "id");
645
+ let headers;
646
+ try {
647
+ headers = sign({
648
+ body,
649
+ secret,
650
+ ...id !== void 0 ? { id } : {},
651
+ ...ts !== void 0 ? { timestamp: Number(ts) } : {}
652
+ });
653
+ } catch (err) {
654
+ throw new UsageError(err.message);
655
+ }
656
+ if (parsed.flags.json === true) io.stdout(`${JSON.stringify(headers, null, 2)}
657
+ `);
658
+ else for (const [k, v] of Object.entries(headers)) io.stdout(`${k}: ${v}
659
+ `);
660
+ return 0;
661
+ }
662
+ async function cmdSend(args, io) {
663
+ const parsed = parseArgs(args, {
664
+ secret: "string",
665
+ event: "string",
666
+ data: "string",
667
+ file: "string",
668
+ id: "string",
669
+ retries: "string",
670
+ timeout: "string",
671
+ "allow-private": "boolean",
672
+ json: "boolean"
673
+ });
674
+ if (parsed.positionals.length === 0) throw new UsageError("Missing <url> (hooksend send <url> ...)");
675
+ if (parsed.positionals.length > 1) throw new UsageError(`Unexpected argument "${parsed.positionals[1]}"`);
676
+ const url = parsed.positionals[0];
677
+ const secret = secretFrom(parsed, io);
678
+ const event = str(parsed.flags, "event");
679
+ if (!event) throw new UsageError("Missing --event <type>");
680
+ const raw = await bodyFrom(parsed);
681
+ let data;
682
+ try {
683
+ data = JSON.parse(raw);
684
+ } catch {
685
+ throw new UsageError("Payload is not valid JSON");
686
+ }
687
+ try {
688
+ sign({ body: "", secret });
689
+ } catch (err) {
690
+ throw new UsageError(err.message);
691
+ }
692
+ const retries = intFlag(parsed.flags, "retries", 3, 0);
693
+ const timeoutMs = intFlag(parsed.flags, "timeout", 15e3, 1);
694
+ const json = parsed.flags.json === true;
695
+ const id = str(parsed.flags, "id");
696
+ if (!json) io.stdout(`POST ${url} ${event}
697
+ `);
698
+ const result = await deliver(
699
+ { url, secret },
700
+ { type: event, data, ...id !== void 0 ? { id } : {} },
701
+ {
702
+ schedule: cliSchedule(retries),
703
+ timeoutMs,
704
+ allowPrivateNetworks: parsed.flags["allow-private"] === true,
705
+ ...io.sleep ? { sleep: io.sleep } : {},
706
+ onAttempt: (r) => {
707
+ if (!json) io.stdout(formatAttempt(r));
708
+ }
709
+ }
710
+ );
711
+ if (json) {
712
+ io.stdout(`${JSON.stringify(result, null, 2)}
713
+ `);
714
+ } else {
715
+ const n = result.attempts.length;
716
+ const tries = `${n} attempt${n === 1 ? "" : "s"}`;
717
+ const last = result.attempts[n - 1];
718
+ if (result.delivered) io.stdout(`\u2714 delivered after ${tries} (${result.id})
719
+ `);
720
+ else if (result.disabled) io.stdout(`\u2716 endpoint answered 410 Gone: remove this endpoint
721
+ `);
722
+ else io.stdout(`\u2716 not delivered after ${tries}${last?.error ? `: ${last.error}` : ""}
723
+ `);
724
+ }
725
+ return result.delivered ? 0 : 1;
726
+ }
727
+ async function runCli(argv, io = defaultIO) {
728
+ const [command, ...rest] = argv;
729
+ try {
730
+ if (command === void 0 || command === "--help" || command === "-h" || command === "help") {
731
+ io.stdout(HELP);
732
+ return 0;
733
+ }
734
+ if (command === "--version" || command === "-v") {
735
+ io.stdout(`${VERSION}
736
+ `);
737
+ return 0;
738
+ }
739
+ if (rest.includes("--help") || rest.includes("-h")) {
740
+ io.stdout(HELP);
741
+ return 0;
742
+ }
743
+ switch (command) {
744
+ case "secret":
745
+ return cmdSecret(rest, io);
746
+ case "sign":
747
+ return await cmdSign(rest, io);
748
+ case "send":
749
+ return await cmdSend(rest, io);
750
+ default:
751
+ throw new UsageError(`Unknown command "${command}"`);
752
+ }
753
+ } catch (err) {
754
+ const message = err instanceof Error ? err.message : String(err);
755
+ io.stderr(`hooksend: ${message}
756
+ `);
757
+ if (err instanceof UsageError) io.stderr(`Run "hooksend --help" for usage.
758
+ `);
759
+ return 2;
760
+ }
761
+ }
762
+
763
+ // src/cli.ts
764
+ runCli(process.argv.slice(2)).then((code) => {
765
+ process.exitCode = code;
766
+ });