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.
@@ -0,0 +1,501 @@
1
+ // src/sign.ts
2
+ import { createHmac, randomBytes } from "crypto";
3
+ var SECRET_PREFIX = "whsec_";
4
+ var BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
5
+ function generateSecret() {
6
+ return SECRET_PREFIX + randomBytes(32).toString("base64");
7
+ }
8
+ var ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
9
+ function createMessageId() {
10
+ let id = "msg_";
11
+ while (id.length < 28) {
12
+ for (const byte of randomBytes(32)) {
13
+ if (byte < 248 && id.length < 28) id += ALPHABET[byte % 62];
14
+ }
15
+ }
16
+ return id;
17
+ }
18
+ function decodeSecret(secret) {
19
+ if (typeof secret !== "string") throw new TypeError("Secret must be a string");
20
+ const raw = secret.startsWith(SECRET_PREFIX) ? secret.slice(SECRET_PREFIX.length) : secret;
21
+ if (raw.length === 0 || !BASE64.test(raw)) {
22
+ throw new TypeError('Invalid secret: expected "whsec_" followed by base64 (use generateSecret())');
23
+ }
24
+ return Buffer.from(raw, "base64");
25
+ }
26
+ function toSeconds(timestamp) {
27
+ if (timestamp === void 0) return Math.floor(Date.now() / 1e3);
28
+ if (timestamp instanceof Date) return Math.floor(timestamp.getTime() / 1e3);
29
+ if (!Number.isFinite(timestamp)) throw new TypeError("Invalid timestamp");
30
+ return Math.floor(timestamp);
31
+ }
32
+ function secretList(options) {
33
+ const list = [];
34
+ if (Array.isArray(options.secret)) list.push(...options.secret);
35
+ else if (options.secret !== void 0) list.push(options.secret);
36
+ if (options.secrets) list.push(...options.secrets);
37
+ if (list.length === 0) throw new TypeError("A secret is required to sign a webhook");
38
+ return list;
39
+ }
40
+ function sign(options) {
41
+ const id = options.id ?? createMessageId();
42
+ if (typeof id !== "string" || id.length === 0) throw new TypeError("Message id must be a non-empty string");
43
+ const timestamp = toSeconds(options.timestamp);
44
+ const body = typeof options.body === "string" ? Buffer.from(options.body, "utf8") : options.body;
45
+ if (!(body instanceof Uint8Array)) throw new TypeError("Body must be a string or Uint8Array");
46
+ const keys = secretList(options).map(decodeSecret);
47
+ const prefix = Buffer.from(`${id}.${timestamp}.`, "utf8");
48
+ const signatures = keys.map(
49
+ (key) => "v1," + createHmac("sha256", key).update(prefix).update(body).digest("base64")
50
+ );
51
+ return {
52
+ "webhook-id": id,
53
+ "webhook-timestamp": String(timestamp),
54
+ "webhook-signature": signatures.join(" ")
55
+ };
56
+ }
57
+
58
+ // src/ssrf.ts
59
+ import { lookup as dnsLookup } from "dns";
60
+ import { isIP } from "net";
61
+ var BlockedError = class extends Error {
62
+ code = "HOOKSEND_BLOCKED";
63
+ constructor(message) {
64
+ super(message);
65
+ this.name = "BlockedError";
66
+ }
67
+ };
68
+ function parseIPv4(ip) {
69
+ const parts = ip.split(".");
70
+ if (parts.length !== 4) return null;
71
+ const out = [];
72
+ for (const part of parts) {
73
+ if (!/^\d{1,3}$/.test(part)) return null;
74
+ const n = Number(part);
75
+ if (n > 255) return null;
76
+ out.push(n);
77
+ }
78
+ return out;
79
+ }
80
+ function ipv4Private(b) {
81
+ const [a, c] = [b[0], b[1]];
82
+ const d = b[2];
83
+ return a === 0 || // "this" network
84
+ a === 10 || // private
85
+ a === 100 && c >= 64 && c <= 127 || // CGNAT 100.64/10
86
+ a === 127 || // loopback
87
+ a === 169 && c === 254 || // link-local, cloud metadata
88
+ a === 172 && c >= 16 && c <= 31 || // private
89
+ a === 192 && c === 0 && d === 0 || // IETF protocol assignments
90
+ a === 192 && c === 0 && d === 2 || // TEST-NET-1
91
+ a === 192 && c === 88 && d === 99 || // 6to4 relay anycast
92
+ a === 192 && c === 168 || // private
93
+ a === 198 && (c === 18 || c === 19) || // benchmarking
94
+ a === 198 && c === 51 && d === 100 || // TEST-NET-2
95
+ a === 203 && c === 0 && d === 113 || // TEST-NET-3
96
+ a >= 224;
97
+ }
98
+ function parseIPv6(input) {
99
+ let ip = input;
100
+ const zone = ip.indexOf("%");
101
+ if (zone !== -1) ip = ip.slice(0, zone);
102
+ if (isIP(ip) !== 6) return null;
103
+ const lastColon = ip.lastIndexOf(":");
104
+ const tail = ip.slice(lastColon + 1);
105
+ if (tail.includes(".")) {
106
+ const v4 = parseIPv4(tail);
107
+ if (!v4) return null;
108
+ ip = `${ip.slice(0, lastColon + 1)}${(v4[0] << 8 | v4[1]).toString(16)}:${(v4[2] << 8 | v4[3]).toString(16)}`;
109
+ }
110
+ const [head, rest] = ip.split("::");
111
+ const headParts = head ? head.split(":") : [];
112
+ const restParts = rest !== void 0 && rest !== "" ? rest.split(":") : [];
113
+ const fill = rest !== void 0 ? 8 - headParts.length - restParts.length : 0;
114
+ const hextets = [...headParts, ...Array(Math.max(fill, 0)).fill("0"), ...restParts].map(
115
+ (h) => parseInt(h, 16)
116
+ );
117
+ if (hextets.length !== 8 || hextets.some((h) => Number.isNaN(h))) return null;
118
+ return hextets;
119
+ }
120
+ function embeddedV4(h, from) {
121
+ return [h[from] >> 8, h[from] & 255, h[from + 1] >> 8, h[from + 1] & 255];
122
+ }
123
+ function ipv6Private(h) {
124
+ const zeroUntil = (n) => h.slice(0, n).every((x) => x === 0);
125
+ if (zeroUntil(8)) return true;
126
+ if (zeroUntil(7) && h[7] === 1) return true;
127
+ if (zeroUntil(5) && h[5] === 65535) return ipv4Private(embeddedV4(h, 6));
128
+ if (zeroUntil(6)) return true;
129
+ if (zeroUntil(4) && h[4] === 65535 && h[5] === 0) return true;
130
+ if (h[0] === 100 && h[1] === 65435 && h.slice(2, 6).every((x) => x === 0)) {
131
+ return ipv4Private(embeddedV4(h, 6));
132
+ }
133
+ if (h[0] === 8194) return ipv4Private(embeddedV4(h, 1));
134
+ const first = h[0];
135
+ return (first & 65024) === 64512 || // unique local fc00::/7
136
+ (first & 65472) === 65152 || // link-local fe80::/10
137
+ (first & 65472) === 65216 || // site-local fec0::/10 (deprecated)
138
+ (first & 65280) === 65280 || // multicast ff00::/8
139
+ first === 8193 && h[1] === 3512 || // documentation 2001:db8::/32
140
+ first === 256 && h[1] === 0 && h[2] === 0 && h[3] === 0;
141
+ }
142
+ function isPrivateAddress(ip) {
143
+ const raw = ip.startsWith("[") && ip.endsWith("]") ? ip.slice(1, -1) : ip;
144
+ const v4 = parseIPv4(raw);
145
+ if (v4) return ipv4Private(v4);
146
+ const v6 = parseIPv6(raw);
147
+ if (v6) return ipv6Private(v6);
148
+ return true;
149
+ }
150
+ function bareHost(hostname) {
151
+ const h = hostname.toLowerCase();
152
+ return h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
153
+ }
154
+ function allowSet(policy) {
155
+ return new Set((policy.allowHosts ?? []).map(bareHost));
156
+ }
157
+ function checkUrl(url, policy = {}) {
158
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
159
+ throw new BlockedError(`Blocked: only http: and https: URLs are allowed (got ${url.protocol})`);
160
+ }
161
+ if (policy.allowPrivateNetworks) return;
162
+ const host = bareHost(url.hostname);
163
+ if (allowSet(policy).has(host)) return;
164
+ if (isIP(host) !== 0 && isPrivateAddress(host)) {
165
+ throw new BlockedError(`Blocked: ${url.hostname} is a private address${host === url.hostname ? "" : ` (${host})`}`);
166
+ }
167
+ }
168
+ var defaultResolver = (hostname) => new Promise((resolve, reject) => {
169
+ dnsLookup(hostname, { all: true, family: 0 }, (err, addresses) => {
170
+ if (err) reject(err);
171
+ else resolve(addresses);
172
+ });
173
+ });
174
+ function createSafeLookup(policy = {}) {
175
+ const resolver = policy.resolver ?? defaultResolver;
176
+ const allowed = allowSet(policy);
177
+ return (hostname, options, callback) => {
178
+ const opts = typeof options === "object" && options !== null ? options : {};
179
+ const family = opts.family === 4 || opts.family === "IPv4" ? 4 : opts.family === 6 || opts.family === "IPv6" ? 6 : 0;
180
+ resolver(hostname).then(
181
+ (all) => {
182
+ const addresses = family === 0 ? all : all.filter((a) => a.family === family);
183
+ if (addresses.length === 0) {
184
+ const err = new Error(`getaddrinfo ENOTFOUND ${hostname}`);
185
+ err.code = "ENOTFOUND";
186
+ callback(err, "");
187
+ return;
188
+ }
189
+ const skip = policy.allowPrivateNetworks || allowed.has(bareHost(hostname));
190
+ if (!skip) {
191
+ for (const a of addresses) {
192
+ if (isPrivateAddress(a.address) && !allowed.has(bareHost(a.address))) {
193
+ callback(new BlockedError(`Blocked: ${hostname} resolves to a private address (${a.address})`), "");
194
+ return;
195
+ }
196
+ }
197
+ }
198
+ if (opts.all) callback(null, addresses);
199
+ else callback(null, addresses[0].address, addresses[0].family);
200
+ },
201
+ (err) => callback(err, "")
202
+ );
203
+ };
204
+ }
205
+
206
+ // src/version.ts
207
+ var VERSION = true ? "1.1.0" : "dev";
208
+
209
+ // src/send.ts
210
+ import http from "http";
211
+ import https from "https";
212
+ var MAX_RESPONSE_BYTES = 2048;
213
+ var DEFAULT_TIMEOUT_MS = 15e3;
214
+ function prepareMessage(message, now = Date.now) {
215
+ const id = message.id ?? createMessageId();
216
+ if (message.body !== void 0) {
217
+ const body = typeof message.body === "string" ? Buffer.from(message.body, "utf8") : message.body;
218
+ return { id, body };
219
+ }
220
+ if (typeof message.type !== "string" || message.type.length === 0) {
221
+ throw new TypeError("Message needs a `type` (or a raw `body`)");
222
+ }
223
+ const date = message.timestamp === void 0 ? new Date(now()) : new Date(message.timestamp);
224
+ if (Number.isNaN(date.getTime())) throw new TypeError("Invalid message timestamp");
225
+ const timestamp = date.toISOString();
226
+ const json = JSON.stringify({ type: message.type, timestamp, data: message.data ?? null });
227
+ return { id, body: Buffer.from(json, "utf8") };
228
+ }
229
+ function parseRetryAfter(value, now = Date.now()) {
230
+ if (value === void 0) return void 0;
231
+ const v = value.trim();
232
+ if (v === "") return void 0;
233
+ if (/^\d+(\.\d+)?$/.test(v)) return Math.round(Number(v) * 1e3);
234
+ const date = Date.parse(v);
235
+ if (Number.isNaN(date)) return void 0;
236
+ return Math.max(0, date - now);
237
+ }
238
+ function describeError(err) {
239
+ if (err instanceof BlockedError) return { message: err.message, type: "blocked" };
240
+ if (err instanceof AggregateError) {
241
+ const blocked = err.errors.find((e) => e instanceof BlockedError);
242
+ if (blocked) return { message: blocked.message, type: "blocked" };
243
+ const first = err.errors[0];
244
+ if (first) return describeError(first);
245
+ }
246
+ if (err instanceof Error) {
247
+ const code = err.code;
248
+ return { message: err.message || code || "Network error", type: "network" };
249
+ }
250
+ return { message: String(err), type: "network" };
251
+ }
252
+ function lowerHeaders(headers) {
253
+ const out = {};
254
+ if (headers) for (const [k, v] of Object.entries(headers)) out[k.toLowerCase()] = String(v);
255
+ return out;
256
+ }
257
+ async function sendOnce(endpoint, message, options = {}) {
258
+ const now = options.now ?? Date.now;
259
+ const attempt = options.attempt ?? 1;
260
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
261
+ const prepared = "body" in message && message.body instanceof Uint8Array && typeof message.id === "string" ? message : prepareMessage(message, now);
262
+ const started = performance.now();
263
+ const base = { attempt, url: endpoint.url, id: prepared.id };
264
+ const fail = (error, errorType) => ({
265
+ ...base,
266
+ ok: false,
267
+ status: null,
268
+ durationMs: Math.round(performance.now() - started),
269
+ error,
270
+ errorType
271
+ });
272
+ let url;
273
+ try {
274
+ url = new URL(endpoint.url);
275
+ } catch {
276
+ return fail(`Invalid URL: ${endpoint.url}`, "invalid");
277
+ }
278
+ try {
279
+ checkUrl(url, options);
280
+ } catch (err) {
281
+ return fail(err.message, "blocked");
282
+ }
283
+ if (options.signal?.aborted) return fail("Aborted", "aborted");
284
+ const signature = sign({
285
+ id: prepared.id,
286
+ timestamp: Math.floor(now() / 1e3),
287
+ body: prepared.body,
288
+ secret: endpoint.secret
289
+ });
290
+ const headers = {
291
+ "content-type": "application/json",
292
+ "user-agent": `hooksend/${VERSION}`,
293
+ ...lowerHeaders(options.headers),
294
+ ...lowerHeaders(endpoint.headers),
295
+ ...signature,
296
+ "content-length": String(prepared.body.byteLength)
297
+ };
298
+ const mod = url.protocol === "https:" ? https : http;
299
+ return new Promise((resolve) => {
300
+ let settled = false;
301
+ const finish = (result) => {
302
+ if (settled) return;
303
+ settled = true;
304
+ clearTimeout(timer);
305
+ options.signal?.removeEventListener("abort", onAbort);
306
+ resolve(result);
307
+ };
308
+ let failure;
309
+ const req = mod.request(url, {
310
+ method: "POST",
311
+ headers,
312
+ agent: false,
313
+ lookup: createSafeLookup(options)
314
+ });
315
+ const timer = setTimeout(() => {
316
+ failure = { message: `Timed out after ${timeoutMs}ms`, type: "timeout" };
317
+ req.destroy(new Error(failure.message));
318
+ }, timeoutMs);
319
+ const onAbort = () => {
320
+ failure = { message: "Aborted", type: "aborted" };
321
+ req.destroy(new Error("Aborted"));
322
+ };
323
+ options.signal?.addEventListener("abort", onAbort, { once: true });
324
+ req.on("error", (err) => {
325
+ const info = failure ?? describeError(err);
326
+ finish(fail(info.message, info.type));
327
+ });
328
+ req.on("response", (res) => {
329
+ const status = res.statusCode ?? 0;
330
+ const durationMs = Math.round(performance.now() - started);
331
+ const chunks = [];
332
+ let size = 0;
333
+ const done = () => {
334
+ const responseBody = Buffer.concat(chunks).subarray(0, MAX_RESPONSE_BYTES).toString("utf8");
335
+ const retryAfter = res.headers["retry-after"];
336
+ const retryAfterMs = parseRetryAfter(Array.isArray(retryAfter) ? retryAfter[0] : retryAfter, now());
337
+ const ok = status >= 200 && status < 300;
338
+ let error;
339
+ if (!ok) {
340
+ error = status >= 300 && status < 400 ? `Redirect not followed (${status}${res.headers.location ? ` to ${res.headers.location}` : ""})` : `HTTP ${status}${res.statusMessage ? ` ${res.statusMessage}` : ""}`;
341
+ }
342
+ finish({
343
+ ...base,
344
+ ok,
345
+ status,
346
+ ...res.statusMessage ? { statusText: res.statusMessage } : {},
347
+ durationMs,
348
+ ...error !== void 0 ? { error } : {},
349
+ ...responseBody !== "" ? { responseBody } : {},
350
+ ...retryAfterMs !== void 0 ? { retryAfterMs } : {}
351
+ });
352
+ res.destroy();
353
+ };
354
+ res.on("data", (chunk) => {
355
+ if (size >= MAX_RESPONSE_BYTES) return;
356
+ chunks.push(chunk);
357
+ size += chunk.length;
358
+ if (size >= MAX_RESPONSE_BYTES) done();
359
+ });
360
+ res.on("end", done);
361
+ res.on("error", done);
362
+ res.on("close", done);
363
+ });
364
+ req.end(prepared.body);
365
+ });
366
+ }
367
+
368
+ // src/deliver.ts
369
+ var SECOND = 1e3;
370
+ var MINUTE = 60 * SECOND;
371
+ var HOUR = 60 * MINUTE;
372
+ var DEFAULT_SCHEDULE = Object.freeze([
373
+ 0,
374
+ 5 * SECOND,
375
+ 5 * MINUTE,
376
+ 30 * MINUTE,
377
+ 2 * HOUR,
378
+ 5 * HOUR,
379
+ 10 * HOUR,
380
+ 10 * HOUR
381
+ ]);
382
+ var DEFAULT_JITTER = 0.2;
383
+ var DEFAULT_MAX_RETRY_AFTER_MS = HOUR;
384
+ function shouldRetry(result) {
385
+ if (result.ok) return false;
386
+ if (result.status === null) return result.errorType === "network" || result.errorType === "timeout";
387
+ return result.status === 408 || result.status === 429 || result.status >= 500;
388
+ }
389
+ var defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
390
+ if (signal?.aborted) {
391
+ reject(new Error("Aborted"));
392
+ return;
393
+ }
394
+ const timer = setTimeout(() => {
395
+ signal?.removeEventListener("abort", onAbort);
396
+ resolve();
397
+ }, ms);
398
+ const onAbort = () => {
399
+ clearTimeout(timer);
400
+ reject(new Error("Aborted"));
401
+ };
402
+ signal?.addEventListener("abort", onAbort, { once: true });
403
+ });
404
+ function applyJitter(ms, jitter = DEFAULT_JITTER, random = Math.random) {
405
+ if (ms <= 0 || jitter <= 0) return Math.max(0, ms);
406
+ return Math.max(0, Math.round(ms * (1 + (random() * 2 - 1) * jitter)));
407
+ }
408
+ function safeCall(fn, arg) {
409
+ if (!fn) return;
410
+ try {
411
+ fn(arg);
412
+ } catch {
413
+ }
414
+ }
415
+ async function deliverWith(endpoint, message, options = {}, hooks = {}) {
416
+ const now = options.now ?? Date.now;
417
+ const schedule = options.schedule ?? DEFAULT_SCHEDULE;
418
+ if (schedule.length === 0 || schedule.some((ms) => !Number.isFinite(ms) || ms < 0)) {
419
+ throw new TypeError("schedule must be a non-empty array of waits in ms (>= 0)");
420
+ }
421
+ const jitter = options.jitter ?? DEFAULT_JITTER;
422
+ const random = options.random ?? Math.random;
423
+ const sleep = options.sleep ?? defaultSleep;
424
+ const retryOn = options.retryOn ?? shouldRetry;
425
+ const maxRetryAfter = options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS;
426
+ const limit = hooks.limit ?? ((fn) => fn());
427
+ const start = Math.max(1, Math.floor(options.startAttempt ?? 1));
428
+ const prepared = "body" in message && message.body instanceof Uint8Array && typeof message.id === "string" ? message : prepareMessage(message, now);
429
+ const attempts = [];
430
+ const result = (extra = {}) => ({
431
+ delivered: false,
432
+ disabled: false,
433
+ aborted: false,
434
+ id: prepared.id,
435
+ attempts,
436
+ ...extra
437
+ });
438
+ let wait = start === 1 ? applyJitter(schedule[0], jitter, random) : 0;
439
+ for (let attempt = start; attempt <= schedule.length; attempt++) {
440
+ if (wait > 0) {
441
+ try {
442
+ await sleep(wait, hooks.waitSignal ?? options.signal);
443
+ } catch {
444
+ return result({ aborted: true });
445
+ }
446
+ }
447
+ if (options.signal?.aborted || hooks.waitSignal?.aborted) return result({ aborted: true });
448
+ const sendOptions = { ...options, attempt };
449
+ const res = await limit(() => sendOnce(endpoint, prepared, sendOptions));
450
+ attempts.push(res);
451
+ if (res.ok) {
452
+ safeCall(options.onAttempt, res);
453
+ return result({ delivered: true });
454
+ }
455
+ if (res.status === 410) {
456
+ safeCall(options.onAttempt, res);
457
+ return result({ disabled: true });
458
+ }
459
+ if (res.errorType === "aborted") {
460
+ safeCall(options.onAttempt, res);
461
+ return result({ aborted: true });
462
+ }
463
+ const retry = attempt < schedule.length && retryOn(res);
464
+ if (!retry) {
465
+ safeCall(options.onAttempt, res);
466
+ return result();
467
+ }
468
+ wait = applyJitter(schedule[attempt], jitter, random);
469
+ if (res.retryAfterMs !== void 0) wait = Math.max(wait, Math.min(res.retryAfterMs, maxRetryAfter));
470
+ res.retryInMs = wait;
471
+ safeCall(options.onAttempt, res);
472
+ if (hooks.onRetryScheduled) await hooks.onRetryScheduled(attempt + 1, wait);
473
+ }
474
+ return result();
475
+ }
476
+ function deliver(endpoint, message, options = {}) {
477
+ return deliverWith(endpoint, message, options);
478
+ }
479
+
480
+ export {
481
+ generateSecret,
482
+ createMessageId,
483
+ decodeSecret,
484
+ sign,
485
+ BlockedError,
486
+ isPrivateAddress,
487
+ checkUrl,
488
+ createSafeLookup,
489
+ VERSION,
490
+ DEFAULT_TIMEOUT_MS,
491
+ prepareMessage,
492
+ parseRetryAfter,
493
+ sendOnce,
494
+ DEFAULT_SCHEDULE,
495
+ DEFAULT_JITTER,
496
+ DEFAULT_MAX_RETRY_AFTER_MS,
497
+ shouldRetry,
498
+ applyJitter,
499
+ deliverWith,
500
+ deliver
501
+ };