@cronwatch/sdk 0.3.1 → 0.5.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/README.md +8 -2
- package/dist/anthropic.d.cts +1 -1
- package/dist/anthropic.d.ts +1 -1
- package/dist/bugsnag.cjs +108 -0
- package/dist/bugsnag.cjs.map +1 -0
- package/dist/bugsnag.d.cts +26 -0
- package/dist/bugsnag.d.ts +26 -0
- package/dist/bugsnag.js +106 -0
- package/dist/bugsnag.js.map +1 -0
- package/dist/client-B7bqnkI5.d.cts +450 -0
- package/dist/client-pmqH3apS.d.ts +450 -0
- package/dist/d1.cjs +214 -0
- package/dist/d1.cjs.map +1 -0
- package/dist/d1.d.cts +42 -0
- package/dist/d1.d.ts +42 -0
- package/dist/d1.js +212 -0
- package/dist/d1.js.map +1 -0
- package/dist/datadog.cjs +95 -0
- package/dist/datadog.cjs.map +1 -0
- package/dist/datadog.d.cts +24 -0
- package/dist/datadog.d.ts +24 -0
- package/dist/datadog.js +93 -0
- package/dist/datadog.js.map +1 -0
- package/dist/discord.cjs +2 -0
- package/dist/discord.cjs.map +1 -1
- package/dist/discord.d.cts +1 -1
- package/dist/discord.d.ts +1 -1
- package/dist/discord.js +2 -0
- package/dist/discord.js.map +1 -1
- package/dist/email-BJ-z_epD.d.cts +21 -0
- package/dist/email-_H0faCh3.d.ts +21 -0
- package/dist/honeybadger.cjs +101 -0
- package/dist/honeybadger.cjs.map +1 -0
- package/dist/honeybadger.d.cts +23 -0
- package/dist/honeybadger.d.ts +23 -0
- package/dist/honeybadger.js +99 -0
- package/dist/honeybadger.js.map +1 -0
- package/dist/index.cjs +1238 -179
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -260
- package/dist/index.d.ts +5 -260
- package/dist/index.js +1238 -179
- package/dist/index.js.map +1 -1
- package/dist/mailgun.cjs +115 -0
- package/dist/mailgun.cjs.map +1 -0
- package/dist/mailgun.d.cts +21 -0
- package/dist/mailgun.d.ts +21 -0
- package/dist/mailgun.js +113 -0
- package/dist/mailgun.js.map +1 -0
- package/dist/newrelic.cjs +88 -0
- package/dist/newrelic.cjs.map +1 -0
- package/dist/newrelic.d.cts +25 -0
- package/dist/newrelic.d.ts +25 -0
- package/dist/newrelic.js +86 -0
- package/dist/newrelic.js.map +1 -0
- package/dist/node.cjs +191 -0
- package/dist/node.cjs.map +1 -0
- package/dist/node.d.cts +97 -0
- package/dist/node.d.ts +97 -0
- package/dist/node.js +186 -0
- package/dist/node.js.map +1 -0
- package/dist/pg-cron.cjs +286 -0
- package/dist/pg-cron.cjs.map +1 -0
- package/dist/pg-cron.d.cts +93 -0
- package/dist/pg-cron.d.ts +93 -0
- package/dist/pg-cron.js +280 -0
- package/dist/pg-cron.js.map +1 -0
- package/dist/postgres.cjs +20 -0
- package/dist/postgres.cjs.map +1 -1
- package/dist/postgres.d.cts +1 -1
- package/dist/postgres.d.ts +1 -1
- package/dist/postgres.js +20 -0
- package/dist/postgres.js.map +1 -1
- package/dist/postmark.cjs +106 -0
- package/dist/postmark.cjs.map +1 -0
- package/dist/postmark.d.cts +18 -0
- package/dist/postmark.d.ts +18 -0
- package/dist/postmark.js +104 -0
- package/dist/postmark.js.map +1 -0
- package/dist/resend.cjs +114 -0
- package/dist/resend.cjs.map +1 -0
- package/dist/resend.d.cts +16 -0
- package/dist/resend.d.ts +16 -0
- package/dist/resend.js +112 -0
- package/dist/resend.js.map +1 -0
- package/dist/rollbar.cjs +108 -0
- package/dist/rollbar.cjs.map +1 -0
- package/dist/rollbar.d.cts +20 -0
- package/dist/rollbar.d.ts +20 -0
- package/dist/rollbar.js +106 -0
- package/dist/rollbar.js.map +1 -0
- package/dist/sendgrid.cjs +114 -0
- package/dist/sendgrid.cjs.map +1 -0
- package/dist/sendgrid.d.cts +19 -0
- package/dist/sendgrid.d.ts +19 -0
- package/dist/sendgrid.js +112 -0
- package/dist/sendgrid.js.map +1 -0
- package/dist/sentry.cjs +130 -0
- package/dist/sentry.cjs.map +1 -0
- package/dist/sentry.d.cts +28 -0
- package/dist/sentry.d.ts +28 -0
- package/dist/sentry.js +127 -0
- package/dist/sentry.js.map +1 -0
- package/dist/ses.cjs +170 -0
- package/dist/ses.cjs.map +1 -0
- package/dist/ses.d.cts +25 -0
- package/dist/ses.d.ts +25 -0
- package/dist/ses.js +168 -0
- package/dist/ses.js.map +1 -0
- package/dist/slack.cjs +2 -0
- package/dist/slack.cjs.map +1 -1
- package/dist/slack.d.cts +1 -1
- package/dist/slack.d.ts +1 -1
- package/dist/slack.js +2 -0
- package/dist/slack.js.map +1 -1
- package/dist/sqlite.cjs +18 -0
- package/dist/sqlite.cjs.map +1 -1
- package/dist/sqlite.d.cts +1 -1
- package/dist/sqlite.d.ts +1 -1
- package/dist/sqlite.js +18 -0
- package/dist/sqlite.js.map +1 -1
- package/dist/twilio.cjs +168 -0
- package/dist/twilio.cjs.map +1 -0
- package/dist/twilio.d.cts +52 -0
- package/dist/twilio.d.ts +52 -0
- package/dist/twilio.js +162 -0
- package/dist/twilio.js.map +1 -0
- package/dist/{types-DUt2apl0.d.cts → types-Ddq1MUPL.d.cts} +29 -2
- package/dist/{types-DUt2apl0.d.ts → types-Ddq1MUPL.d.ts} +29 -2
- package/dist/webhook.cjs +11 -5
- package/dist/webhook.cjs.map +1 -1
- package/dist/webhook.d.cts +6 -3
- package/dist/webhook.d.ts +6 -3
- package/dist/webhook.js +11 -6
- package/dist/webhook.js.map +1 -1
- package/package.json +208 -2
package/dist/twilio.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { A as Alert, a as AlertChannel } from './types-Ddq1MUPL.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Twilio SMS. API reference: https://www.twilio.com/docs/messaging/api/message-resource
|
|
5
|
+
* POST https://api.twilio.com/2010-04-01/Accounts/<AccountSid>/Messages.json,
|
|
6
|
+
* form encoded, with basic auth. One recipient per request.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
interface TwilioOptions {
|
|
10
|
+
/** The account SID, "AC...". It is in the URL whichever credentials sign the request. */
|
|
11
|
+
accountSid: string;
|
|
12
|
+
/** The account's auth token. Or pass apiKeySid and apiKeySecret instead. */
|
|
13
|
+
authToken?: string;
|
|
14
|
+
/** An API key SID, "SK...", with apiKeySecret, in place of the auth token. */
|
|
15
|
+
apiKeySid?: string;
|
|
16
|
+
apiKeySecret?: string;
|
|
17
|
+
/** A Twilio number in E.164 form, "+15005550006". Or pass messagingServiceSid. */
|
|
18
|
+
from?: string;
|
|
19
|
+
/** A messaging service SID, "MG...", in place of from. */
|
|
20
|
+
messagingServiceSid?: string;
|
|
21
|
+
/** One number in E.164 form, or several; each gets its own message. */
|
|
22
|
+
to: string | string[];
|
|
23
|
+
/** Also text when a job recovers. Defaults to false: a text is for what needs a person. */
|
|
24
|
+
recovered?: boolean;
|
|
25
|
+
/** How many SMS segments a message may use, 1 to 10. Defaults to 3. */
|
|
26
|
+
segments?: number;
|
|
27
|
+
link?: (alert: Alert) => string;
|
|
28
|
+
}
|
|
29
|
+
/** The most segments a message may use, which keeps it inside Twilio's 1600 character Body limit. */
|
|
30
|
+
declare const MAX_SEGMENTS = 10;
|
|
31
|
+
/** Twilio refuses a Body longer than this. */
|
|
32
|
+
declare const MAX_BODY = 1600;
|
|
33
|
+
/**
|
|
34
|
+
* Texts alerts through Twilio, to every number at once. The alert counts as
|
|
35
|
+
* delivered when any number took it; each number that refused it is
|
|
36
|
+
* reported to the client's onError. It fails only when every number did.
|
|
37
|
+
*/
|
|
38
|
+
declare function twilio(options: TwilioOptions): AlertChannel;
|
|
39
|
+
/**
|
|
40
|
+
* The segments `text` takes. A character is never split across two: an
|
|
41
|
+
* extension character (two septets) or a surrogate pair (two UCS-2 units)
|
|
42
|
+
* that would straddle a boundary starts the next segment, as phones pack them.
|
|
43
|
+
*/
|
|
44
|
+
declare function smsSegments(text: string): number;
|
|
45
|
+
/**
|
|
46
|
+
* The title, then as many lines of the message (and the triage) as fit, then
|
|
47
|
+
* the link. The link is kept whole; the text before it is cut to make room.
|
|
48
|
+
* `segments` is clamped to 1 to 10.
|
|
49
|
+
*/
|
|
50
|
+
declare function smsBody(alert: Alert, link: string | undefined, segments?: number): string;
|
|
51
|
+
|
|
52
|
+
export { MAX_BODY, MAX_SEGMENTS, type TwilioOptions, smsBody, smsSegments, twilio };
|
package/dist/twilio.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// src/alerts/shared.ts
|
|
2
|
+
var TIMEOUT_MS = 1e4;
|
|
3
|
+
function origin(url) {
|
|
4
|
+
try {
|
|
5
|
+
return new URL(url).origin;
|
|
6
|
+
} catch {
|
|
7
|
+
return "(invalid URL)";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
var ERROR_BODY_MAX = 200;
|
|
11
|
+
async function post(provider, url, init, secrets = []) {
|
|
12
|
+
const response = await fetch(url, { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
13
|
+
if (!response.ok) {
|
|
14
|
+
let text = "";
|
|
15
|
+
try {
|
|
16
|
+
text = await response.text();
|
|
17
|
+
} catch {
|
|
18
|
+
}
|
|
19
|
+
throw new Error(`${provider} ${origin(url)} answered ${response.status}${text ? `: ${errorBody(text, secrets)}` : ""}`);
|
|
20
|
+
}
|
|
21
|
+
return response;
|
|
22
|
+
}
|
|
23
|
+
function errorBody(text, secrets = []) {
|
|
24
|
+
const kept = secrets.filter((s) => typeof s === "string" && s.length >= 4);
|
|
25
|
+
const longest = kept.reduce((n, s) => Math.max(n, s.length), 0);
|
|
26
|
+
let head = cut(text, ERROR_BODY_MAX + longest);
|
|
27
|
+
for (const secret of kept) head = head.split(secret).join("[redacted]");
|
|
28
|
+
return cut(head, ERROR_BODY_MAX);
|
|
29
|
+
}
|
|
30
|
+
function trimmed(value) {
|
|
31
|
+
return typeof value === "string" ? value.trim() : "";
|
|
32
|
+
}
|
|
33
|
+
function base64(text) {
|
|
34
|
+
let binary = "";
|
|
35
|
+
for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
|
|
36
|
+
return btoa(binary);
|
|
37
|
+
}
|
|
38
|
+
function basicAuth(user, password) {
|
|
39
|
+
return `Basic ${base64(`${user}:${password}`)}`;
|
|
40
|
+
}
|
|
41
|
+
function cut(text, max) {
|
|
42
|
+
if (text.length <= max) return text;
|
|
43
|
+
let end = max;
|
|
44
|
+
const code = text.charCodeAt(end - 1);
|
|
45
|
+
if (code >= 55296 && code <= 56319) end -= 1;
|
|
46
|
+
return text.slice(0, end);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/alerts/twilio.ts
|
|
50
|
+
var MAX_SEGMENTS = 10;
|
|
51
|
+
var MAX_BODY = 1600;
|
|
52
|
+
function twilio(options) {
|
|
53
|
+
const accountSid = trimmed(options.accountSid);
|
|
54
|
+
if (!accountSid) throw new Error("twilio() needs an accountSid");
|
|
55
|
+
const apiKeySid = trimmed(options.apiKeySid);
|
|
56
|
+
const user = apiKeySid || accountSid;
|
|
57
|
+
const password = apiKeySid ? trimmed(options.apiKeySecret) : trimmed(options.authToken);
|
|
58
|
+
if (!password) throw new Error("twilio() needs an authToken, or an apiKeySid and apiKeySecret");
|
|
59
|
+
if (!options.from && !options.messagingServiceSid) throw new Error("twilio() needs a from number or a messagingServiceSid");
|
|
60
|
+
const to = (Array.isArray(options.to) ? options.to : [options.to]).filter((n) => typeof n === "string" && n.trim() !== "").map((n) => n.trim());
|
|
61
|
+
if (to.length === 0) throw new Error("twilio() needs at least one to number");
|
|
62
|
+
const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`;
|
|
63
|
+
const authorization = basicAuth(user, password);
|
|
64
|
+
const segments = segmentBudget(options.segments);
|
|
65
|
+
return {
|
|
66
|
+
name: "twilio",
|
|
67
|
+
async send(alert, context) {
|
|
68
|
+
if (alert.type === "recovered" && !options.recovered) return;
|
|
69
|
+
const body = smsBody(alert, options.link?.(alert), segments);
|
|
70
|
+
const results = await Promise.allSettled(to.map((number) => {
|
|
71
|
+
const form = new URLSearchParams();
|
|
72
|
+
form.append("To", number);
|
|
73
|
+
if (options.messagingServiceSid) form.append("MessagingServiceSid", options.messagingServiceSid);
|
|
74
|
+
else form.append("From", options.from);
|
|
75
|
+
form.append("Body", body);
|
|
76
|
+
return post("Twilio", url, { headers: { "content-type": "application/x-www-form-urlencoded", authorization }, body: form.toString() }, [password]);
|
|
77
|
+
}));
|
|
78
|
+
const failed = results.flatMap((r, i) => r.status === "rejected" ? [{ number: to[i], error: r.reason }] : []);
|
|
79
|
+
if (failed.length === 0) return;
|
|
80
|
+
if (failed.length === to.length) {
|
|
81
|
+
const message = failed[0].error.message;
|
|
82
|
+
throw new Error(to.length > 1 ? `${message} (${failed.length} of ${to.length} numbers failed)` : message);
|
|
83
|
+
}
|
|
84
|
+
for (const { number, error } of failed) {
|
|
85
|
+
const report = new Error(`${error.message} (to ${maskNumber(number)}; ${to.length - failed.length} of ${to.length} numbers took the alert)`);
|
|
86
|
+
if (context) context.onError(report);
|
|
87
|
+
else console.error("[cronwatch] alert channel twilio:", report);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function maskNumber(number) {
|
|
93
|
+
return number.length <= 4 ? number : `${"*".repeat(Math.min(number.length - 4, 8))}${number.slice(-4)}`;
|
|
94
|
+
}
|
|
95
|
+
var GSM = `@\xA3$\xA5\xE8\xE9\xF9\xEC\xF2\xC7
|
|
96
|
+
\xD8\xF8\r\xC5\xE5\u0394_\u03A6\u0393\u039B\u03A9\u03A0\u03A8\u03A3\u0398\u039E\xC6\xE6\xDF\xC9 !"#\xA4%&'()*+,-./0123456789:;<=>?\xA1ABCDEFGHIJKLMNOPQRSTUVWXYZ\xC4\xD6\xD1\xDC\xA7\xBFabcdefghijklmnopqrstuvwxyz\xE4\xF6\xF1\xFC\xE0`;
|
|
97
|
+
var GSM_EXTENDED = "^{}\\[~]|\u20AC\f";
|
|
98
|
+
function smsSegments(text) {
|
|
99
|
+
const units = [];
|
|
100
|
+
let gsm = true;
|
|
101
|
+
for (const ch of text) {
|
|
102
|
+
if (GSM.includes(ch)) units.push(1);
|
|
103
|
+
else if (GSM_EXTENDED.includes(ch)) units.push(2);
|
|
104
|
+
else {
|
|
105
|
+
gsm = false;
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const [single, per, sizes] = gsm ? [160, 153, units] : [70, 67, Array.from(text, (ch) => ch.length)];
|
|
110
|
+
const total = sizes.reduce((n, u) => n + u, 0);
|
|
111
|
+
if (total <= single) return 1;
|
|
112
|
+
let count = 1;
|
|
113
|
+
let used = 0;
|
|
114
|
+
for (const u of sizes) {
|
|
115
|
+
if (used + u > per) {
|
|
116
|
+
count += 1;
|
|
117
|
+
used = 0;
|
|
118
|
+
}
|
|
119
|
+
used += u;
|
|
120
|
+
}
|
|
121
|
+
return count;
|
|
122
|
+
}
|
|
123
|
+
function fits(text, segments) {
|
|
124
|
+
return text.length <= MAX_BODY && smsSegments(text) <= segments;
|
|
125
|
+
}
|
|
126
|
+
function smsBody(alert, link, segments = 3) {
|
|
127
|
+
const budget = segmentBudget(segments);
|
|
128
|
+
const tail = link ? `
|
|
129
|
+
${link}` : "";
|
|
130
|
+
const lines = [alert.title, ...alert.message.split("\n").filter((l) => l.trim() !== ""), ...alert.triage ? [`Triage: ${alert.triage}`] : []];
|
|
131
|
+
let text = "";
|
|
132
|
+
for (const line of lines) {
|
|
133
|
+
const next = text ? `${text}
|
|
134
|
+
${line}` : line;
|
|
135
|
+
if (fits(next + tail, budget)) {
|
|
136
|
+
text = next;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const chars = Array.from(line);
|
|
140
|
+
let lo = 0;
|
|
141
|
+
let hi = chars.length;
|
|
142
|
+
while (lo < hi) {
|
|
143
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
144
|
+
const candidate = (text ? `${text}
|
|
145
|
+
` : "") + chars.slice(0, mid).join("") + "...";
|
|
146
|
+
if (fits(candidate + tail, budget)) lo = mid;
|
|
147
|
+
else hi = mid - 1;
|
|
148
|
+
}
|
|
149
|
+
if (lo > 0) text = (text ? `${text}
|
|
150
|
+
` : "") + chars.slice(0, lo).join("") + "...";
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
return cut(text + tail, MAX_BODY);
|
|
154
|
+
}
|
|
155
|
+
function segmentBudget(segments) {
|
|
156
|
+
const n = typeof segments === "number" && Number.isFinite(segments) ? Math.floor(segments) : 3;
|
|
157
|
+
return Math.min(MAX_SEGMENTS, Math.max(1, n));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export { MAX_BODY, MAX_SEGMENTS, smsBody, smsSegments, twilio };
|
|
161
|
+
//# sourceMappingURL=twilio.js.map
|
|
162
|
+
//# sourceMappingURL=twilio.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/twilio.ts"],"names":[],"mappings":";AAOO,IAAM,UAAA,GAAa,GAAA;AAYnB,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,MAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,eAAA;AAAA,EACT;AACF;AAGO,IAAM,cAAA,GAAiB,GAAA;AAW9B,eAAsB,KAAK,QAAA,EAAkB,GAAA,EAAa,IAAA,EAAyD,OAAA,GAAkC,EAAC,EAAsB;AAC1K,EAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,GAAA,EAAK,EAAE,MAAA,EAAQ,MAAA,EAAQ,SAAS,IAAA,CAAK,OAAA,EAAS,MAAM,IAAA,CAAK,IAAA,EAAM,UAAU,OAAA,EAAS,MAAA,EAAQ,YAAY,OAAA,CAAQ,UAAU,GAAG,CAAA;AACxJ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,GAAA,CAAI,YAAA,EAAc,KAAK,GAAA,CAAI,CAAA,EAAG,CAAC,CAAC,CAAA;AAC9C","file":"twilio.js","sourcesContent":["/**\n * Helpers shared by the provider channels. Only fetch and Web Crypto, so the\n * channels run on Node, Cloudflare Workers, Deno and Bun alike. Not an entry\n * point: each channel bundles its own copy.\n */\nimport type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/** How much of a provider's error body goes into the error message. */\nexport const ERROR_BODY_MAX = 200;\n\n/**\n * POSTs and throws on a non-2xx answer. The error names the provider and the\n * URL's origin, plus the start of the response body with every secret the\n * channel holds cut out, in case a provider echoes one back. Secrets are cut\n * from a prefix long enough to hold one that starts inside the first\n * ERROR_BODY_MAX characters, and only then is it cut to that length, so no\n * part of a secret survives at the edge. A redirect is refused rather than\n * followed: the credential headers would go with it to wherever it points.\n */\nexport async function post(provider: string, url: string, init: { headers: Record<string, string>; body: string }, secrets: (string | undefined)[] = []): Promise<Response> {\n const response = await fetch(url, { method: \"POST\", headers: init.headers, body: init.body, redirect: \"error\", signal: AbortSignal.timeout(TIMEOUT_MS) });\n if (!response.ok) {\n let text = \"\";\n try {\n text = await response.text();\n } catch {\n // The status is enough.\n }\n throw new Error(`${provider} ${origin(url)} answered ${response.status}${text ? `: ${errorBody(text, secrets)}` : \"\"}`);\n }\n return response;\n}\n\n/** The start of an error body, secrets cut out first, then cut to ERROR_BODY_MAX on a code point. */\nexport function errorBody(text: string, secrets: (string | undefined)[] = []): string {\n const kept = secrets.filter((s): s is string => typeof s === \"string\" && s.length >= 4);\n const longest = kept.reduce((n, s) => Math.max(n, s.length), 0);\n let head = cut(text, ERROR_BODY_MAX + longest);\n for (const secret of kept) head = head.split(secret).join(\"[redacted]\");\n return cut(head, ERROR_BODY_MAX);\n}\n\n/** A credential with the spaces and newlines a paste leaves around it taken off. Anything not a string is empty. */\nexport function trimmed(value: unknown): string {\n return typeof value === \"string\" ? value.trim() : \"\";\n}\n\n/** Base64 of UTF-8, without Buffer. */\nexport function base64(text: string): string {\n let binary = \"\";\n for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nexport function basicAuth(user: string, password: string): string {\n return `Basic ${base64(`${user}:${password}`)}`;\n}\n\nexport function hex(bytes: ArrayBuffer | Uint8Array): string {\n return Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function sha256Hex(text: string): Promise<string> {\n return hex(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text)));\n}\n\n/**\n * A stable 32 hex character id for one alert: the same job, type and time\n * always give the same id, so a provider that deduplicates on it drops a\n * resend of an alert it already took.\n */\nexport async function alertId(alert: Alert): Promise<string> {\n return (await sha256Hex(`${alert.job}\\n${alert.type}\\n${alert.at}`)).slice(0, 32);\n}\n\n/** The same id laid out as a UUID, for APIs that ask for one. */\nexport function asUuid(id: string): string {\n return `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20, 32)}`;\n}\n\n/** Cuts to at most `max` UTF-16 units without splitting a surrogate pair. */\nexport function cut(text: string, max: number): string {\n if (text.length <= max) return text;\n let end = max;\n const code = text.charCodeAt(end - 1);\n if (code >= 0xd800 && code <= 0xdbff) end -= 1;\n return text.slice(0, end);\n}\n\n/** The run fields worth attaching to a tracker event. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Twilio SMS. API reference: https://www.twilio.com/docs/messaging/api/message-resource\n * POST https://api.twilio.com/2010-04-01/Accounts/<AccountSid>/Messages.json,\n * form encoded, with basic auth. One recipient per request.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { basicAuth, cut, post, trimmed } from \"./shared.js\";\n\nexport interface TwilioOptions {\n /** The account SID, \"AC...\". It is in the URL whichever credentials sign the request. */\n accountSid: string;\n /** The account's auth token. Or pass apiKeySid and apiKeySecret instead. */\n authToken?: string;\n /** An API key SID, \"SK...\", with apiKeySecret, in place of the auth token. */\n apiKeySid?: string;\n apiKeySecret?: string;\n /** A Twilio number in E.164 form, \"+15005550006\". Or pass messagingServiceSid. */\n from?: string;\n /** A messaging service SID, \"MG...\", in place of from. */\n messagingServiceSid?: string;\n /** One number in E.164 form, or several; each gets its own message. */\n to: string | string[];\n /** Also text when a job recovers. Defaults to false: a text is for what needs a person. */\n recovered?: boolean;\n /** How many SMS segments a message may use, 1 to 10. Defaults to 3. */\n segments?: number;\n link?: (alert: Alert) => string;\n}\n\n/** The most segments a message may use, which keeps it inside Twilio's 1600 character Body limit. */\nexport const MAX_SEGMENTS = 10;\n/** Twilio refuses a Body longer than this. */\nexport const MAX_BODY = 1600;\n\n/**\n * Texts alerts through Twilio, to every number at once. The alert counts as\n * delivered when any number took it; each number that refused it is\n * reported to the client's onError. It fails only when every number did.\n */\nexport function twilio(options: TwilioOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which the Authorization header would refuse or send.\n const accountSid = trimmed(options.accountSid);\n if (!accountSid) throw new Error(\"twilio() needs an accountSid\");\n const apiKeySid = trimmed(options.apiKeySid);\n const user = apiKeySid || accountSid;\n const password = apiKeySid ? trimmed(options.apiKeySecret) : trimmed(options.authToken);\n if (!password) throw new Error(\"twilio() needs an authToken, or an apiKeySid and apiKeySecret\");\n if (!options.from && !options.messagingServiceSid) throw new Error(\"twilio() needs a from number or a messagingServiceSid\");\n const to = (Array.isArray(options.to) ? options.to : [options.to]).filter((n) => typeof n === \"string\" && n.trim() !== \"\").map((n) => n.trim());\n if (to.length === 0) throw new Error(\"twilio() needs at least one to number\");\n const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`;\n const authorization = basicAuth(user, password);\n const segments = segmentBudget(options.segments);\n return {\n name: \"twilio\",\n async send(alert, context) {\n if (alert.type === \"recovered\" && !options.recovered) return;\n const body = smsBody(alert, options.link?.(alert), segments);\n const results = await Promise.allSettled(to.map((number) => {\n const form = new URLSearchParams();\n form.append(\"To\", number);\n if (options.messagingServiceSid) form.append(\"MessagingServiceSid\", options.messagingServiceSid);\n else form.append(\"From\", options.from!);\n form.append(\"Body\", body);\n return post(\"Twilio\", url, { headers: { \"content-type\": \"application/x-www-form-urlencoded\", authorization }, body: form.toString() }, [password]);\n }));\n const failed = results.flatMap((r, i) => (r.status === \"rejected\" ? [{ number: to[i]!, error: r.reason as Error }] : []));\n if (failed.length === 0) return;\n if (failed.length === to.length) {\n const message = failed[0]!.error.message;\n throw new Error(to.length > 1 ? `${message} (${failed.length} of ${to.length} numbers failed)` : message);\n }\n // Delivered to someone: counted as sent, so a retry never texts the numbers that took it again.\n for (const { number, error } of failed) {\n const report = new Error(`${error.message} (to ${maskNumber(number)}; ${to.length - failed.length} of ${to.length} numbers took the alert)`);\n if (context) context.onError(report);\n else console.error(\"[cronwatch] alert channel twilio:\", report);\n }\n },\n };\n}\n\n/** A number with all but its last four digits hidden, for an error message. */\nfunction maskNumber(number: string): string {\n return number.length <= 4 ? number : `${\"*\".repeat(Math.min(number.length - 4, 8))}${number.slice(-4)}`;\n}\n\n// The GSM 03.38 alphabet: a message in it takes 153 characters a segment\n// (when split), anything else is UCS-2 at 67. The extension table costs two.\nconst GSM = \"@£$¥èéùìòÇ\\nØø\\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\\\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà\";\nconst GSM_EXTENDED = \"^{}\\\\[~]|€\\f\";\n\n/**\n * The segments `text` takes. A character is never split across two: an\n * extension character (two septets) or a surrogate pair (two UCS-2 units)\n * that would straddle a boundary starts the next segment, as phones pack them.\n */\nexport function smsSegments(text: string): number {\n const units: number[] = [];\n let gsm = true;\n for (const ch of text) {\n if (GSM.includes(ch)) units.push(1);\n else if (GSM_EXTENDED.includes(ch)) units.push(2);\n else {\n gsm = false;\n break;\n }\n }\n const [single, per, sizes] = gsm ? [160, 153, units] : [70, 67, Array.from(text, (ch) => ch.length)];\n const total = sizes.reduce((n, u) => n + u, 0);\n if (total <= single) return 1;\n let count = 1;\n let used = 0;\n for (const u of sizes) {\n if (used + u > per) {\n count += 1;\n used = 0;\n }\n used += u;\n }\n return count;\n}\n\n/** Fits `text` within `segments` SMS segments and Twilio's Body limit. */\nfunction fits(text: string, segments: number): boolean {\n return text.length <= MAX_BODY && smsSegments(text) <= segments;\n}\n\n/**\n * The title, then as many lines of the message (and the triage) as fit, then\n * the link. The link is kept whole; the text before it is cut to make room.\n * `segments` is clamped to 1 to 10.\n */\nexport function smsBody(alert: Alert, link: string | undefined, segments = 3): string {\n const budget = segmentBudget(segments);\n const tail = link ? `\\n${link}` : \"\";\n const lines = [alert.title, ...alert.message.split(\"\\n\").filter((l) => l.trim() !== \"\"), ...(alert.triage ? [`Triage: ${alert.triage}`] : [])];\n let text = \"\";\n for (const line of lines) {\n const next = text ? `${text}\\n${line}` : line;\n if (fits(next + tail, budget)) {\n text = next;\n continue;\n }\n // Part of this line, cut on a code point and marked.\n const chars = Array.from(line);\n let lo = 0;\n let hi = chars.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n const candidate = (text ? `${text}\\n` : \"\") + chars.slice(0, mid).join(\"\") + \"...\";\n if (fits(candidate + tail, budget)) lo = mid;\n else hi = mid - 1;\n }\n if (lo > 0) text = (text ? `${text}\\n` : \"\") + chars.slice(0, lo).join(\"\") + \"...\";\n break;\n }\n // Only a link too long for any budget gets here too long; Twilio would refuse it whole.\n return cut(text + tail, MAX_BODY);\n}\n\n/** A segment count clamped to 1 to MAX_SEGMENTS; 3 for anything not a number. */\nfunction segmentBudget(segments: number | undefined): number {\n const n = typeof segments === \"number\" && Number.isFinite(segments) ? Math.floor(segments) : 3;\n return Math.min(MAX_SEGMENTS, Math.max(1, n));\n}\n"]}
|
|
@@ -131,8 +131,16 @@ interface AlertDetails {
|
|
|
131
131
|
over_budget: {
|
|
132
132
|
breaches: BudgetBreach[];
|
|
133
133
|
};
|
|
134
|
+
/**
|
|
135
|
+
* `after` names the conditions that closed. A recovery with `reason`
|
|
136
|
+
* "unscheduled" closes missed alone because the job no longer has a
|
|
137
|
+
* schedule; `since` is when missed opened. Without `reason`, a successful
|
|
138
|
+
* run closed everything that was open.
|
|
139
|
+
*/
|
|
134
140
|
recovered: {
|
|
135
141
|
after: Condition[];
|
|
142
|
+
reason?: "unscheduled";
|
|
143
|
+
since?: number;
|
|
136
144
|
};
|
|
137
145
|
}
|
|
138
146
|
/** An alert before it has a title and message. See composeAlert(). */
|
|
@@ -166,9 +174,18 @@ type Alert = {
|
|
|
166
174
|
details: AlertDetails[K];
|
|
167
175
|
};
|
|
168
176
|
}[AlertType];
|
|
177
|
+
/** What the client hands a channel with each alert. */
|
|
178
|
+
interface ChannelContext {
|
|
179
|
+
/**
|
|
180
|
+
* Report a problem that did not stop the alert going out, such as one of
|
|
181
|
+
* several recipients refusing it. Goes to the client's onError.
|
|
182
|
+
*/
|
|
183
|
+
onError(error: unknown): void;
|
|
184
|
+
}
|
|
169
185
|
interface AlertChannel {
|
|
170
186
|
name: string;
|
|
171
|
-
|
|
187
|
+
/** Resolves once the alert went out (to at least one recipient); throws when it went nowhere. */
|
|
188
|
+
send(alert: Alert, context?: ChannelContext): Promise<void>;
|
|
172
189
|
}
|
|
173
190
|
interface Store {
|
|
174
191
|
/** Called once before first use. Create tables here. */
|
|
@@ -179,6 +196,16 @@ interface Store {
|
|
|
179
196
|
deleteJob(name: string): Promise<void>;
|
|
180
197
|
insertRun(run: Run): Promise<void>;
|
|
181
198
|
updateRun(run: Run): Promise<void>;
|
|
199
|
+
/**
|
|
200
|
+
* Write a run's status, finishedAt, durationMs, error, output and metrics
|
|
201
|
+
* only when its stored status is one of `fromStatuses`, in one step (SQL:
|
|
202
|
+
* `UPDATE ... WHERE id = ? AND status IN (...)`). Returns whether it wrote.
|
|
203
|
+
* This is what lets exactly one of several processes finishing the same run
|
|
204
|
+
* evaluate it; the others see false and report the run as already finished.
|
|
205
|
+
* A store without it falls back to getRun then updateRun, which is safe only
|
|
206
|
+
* when one process at a time finishes a given run.
|
|
207
|
+
*/
|
|
208
|
+
updateRunIf?(run: Run, fromStatuses: Run["status"][]): Promise<boolean>;
|
|
182
209
|
getRun(id: string): Promise<Run | null>;
|
|
183
210
|
/** Newest first. */
|
|
184
211
|
listRuns(job: string, limit: number): Promise<Run[]>;
|
|
@@ -233,4 +260,4 @@ interface TriageContext {
|
|
|
233
260
|
}
|
|
234
261
|
type TriageFn = (context: TriageContext) => Promise<string | null>;
|
|
235
262
|
|
|
236
|
-
export type { Alert as A, BudgetBreach as B,
|
|
263
|
+
export type { Alert as A, BudgetBreach as B, ChannelContext as C, Duration as D, ExpectRule as E, JobDefinition as J, Run as R, Store as S, TriageContext as T, AlertChannel as a, AlertDraft as b, StoredJobDefinition as c, AlertDetails as d, AlertType as e, CheckResult as f, Condition as g, JobHealth as h, JobOptions as i, JobState as j, JobSummary as k, RunStatus as l, StoredJob as m, TriageFn as n };
|
|
@@ -131,8 +131,16 @@ interface AlertDetails {
|
|
|
131
131
|
over_budget: {
|
|
132
132
|
breaches: BudgetBreach[];
|
|
133
133
|
};
|
|
134
|
+
/**
|
|
135
|
+
* `after` names the conditions that closed. A recovery with `reason`
|
|
136
|
+
* "unscheduled" closes missed alone because the job no longer has a
|
|
137
|
+
* schedule; `since` is when missed opened. Without `reason`, a successful
|
|
138
|
+
* run closed everything that was open.
|
|
139
|
+
*/
|
|
134
140
|
recovered: {
|
|
135
141
|
after: Condition[];
|
|
142
|
+
reason?: "unscheduled";
|
|
143
|
+
since?: number;
|
|
136
144
|
};
|
|
137
145
|
}
|
|
138
146
|
/** An alert before it has a title and message. See composeAlert(). */
|
|
@@ -166,9 +174,18 @@ type Alert = {
|
|
|
166
174
|
details: AlertDetails[K];
|
|
167
175
|
};
|
|
168
176
|
}[AlertType];
|
|
177
|
+
/** What the client hands a channel with each alert. */
|
|
178
|
+
interface ChannelContext {
|
|
179
|
+
/**
|
|
180
|
+
* Report a problem that did not stop the alert going out, such as one of
|
|
181
|
+
* several recipients refusing it. Goes to the client's onError.
|
|
182
|
+
*/
|
|
183
|
+
onError(error: unknown): void;
|
|
184
|
+
}
|
|
169
185
|
interface AlertChannel {
|
|
170
186
|
name: string;
|
|
171
|
-
|
|
187
|
+
/** Resolves once the alert went out (to at least one recipient); throws when it went nowhere. */
|
|
188
|
+
send(alert: Alert, context?: ChannelContext): Promise<void>;
|
|
172
189
|
}
|
|
173
190
|
interface Store {
|
|
174
191
|
/** Called once before first use. Create tables here. */
|
|
@@ -179,6 +196,16 @@ interface Store {
|
|
|
179
196
|
deleteJob(name: string): Promise<void>;
|
|
180
197
|
insertRun(run: Run): Promise<void>;
|
|
181
198
|
updateRun(run: Run): Promise<void>;
|
|
199
|
+
/**
|
|
200
|
+
* Write a run's status, finishedAt, durationMs, error, output and metrics
|
|
201
|
+
* only when its stored status is one of `fromStatuses`, in one step (SQL:
|
|
202
|
+
* `UPDATE ... WHERE id = ? AND status IN (...)`). Returns whether it wrote.
|
|
203
|
+
* This is what lets exactly one of several processes finishing the same run
|
|
204
|
+
* evaluate it; the others see false and report the run as already finished.
|
|
205
|
+
* A store without it falls back to getRun then updateRun, which is safe only
|
|
206
|
+
* when one process at a time finishes a given run.
|
|
207
|
+
*/
|
|
208
|
+
updateRunIf?(run: Run, fromStatuses: Run["status"][]): Promise<boolean>;
|
|
182
209
|
getRun(id: string): Promise<Run | null>;
|
|
183
210
|
/** Newest first. */
|
|
184
211
|
listRuns(job: string, limit: number): Promise<Run[]>;
|
|
@@ -233,4 +260,4 @@ interface TriageContext {
|
|
|
233
260
|
}
|
|
234
261
|
type TriageFn = (context: TriageContext) => Promise<string | null>;
|
|
235
262
|
|
|
236
|
-
export type { Alert as A, BudgetBreach as B,
|
|
263
|
+
export type { Alert as A, BudgetBreach as B, ChannelContext as C, Duration as D, ExpectRule as E, JobDefinition as J, Run as R, Store as S, TriageContext as T, AlertChannel as a, AlertDraft as b, StoredJobDefinition as c, AlertDetails as d, AlertType as e, CheckResult as f, Condition as g, JobHealth as h, JobOptions as i, JobState as j, JobSummary as k, RunStatus as l, StoredJob as m, TriageFn as n };
|
package/dist/webhook.cjs
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var crypto = require('crypto');
|
|
4
|
-
|
|
5
3
|
// src/alerts/webhook.ts
|
|
6
4
|
var TIMEOUT_MS = 1e4;
|
|
7
5
|
function origin(url) {
|
|
@@ -17,16 +15,24 @@ function webhook(options) {
|
|
|
17
15
|
name: "webhook",
|
|
18
16
|
async send(alert) {
|
|
19
17
|
const body = JSON.stringify(alert);
|
|
20
|
-
const headers = { "content-type": "application/json", "user-agent": "cronwatch"
|
|
18
|
+
const headers = { "content-type": "application/json", "user-agent": "cronwatch" };
|
|
19
|
+
for (const [name, value] of Object.entries(options.headers ?? {})) headers[name] = typeof value === "string" ? value.trim() : value;
|
|
21
20
|
if (options.secret) {
|
|
22
|
-
headers["x-cronwatch-signature"] = `sha256=${
|
|
21
|
+
headers["x-cronwatch-signature"] = `sha256=${await hmacSha256Hex(options.secret, body)}`;
|
|
23
22
|
}
|
|
24
|
-
const response = await fetch(options.url, { method: "POST", headers, body, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
23
|
+
const response = await fetch(options.url, { method: "POST", headers, body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
25
24
|
if (!response.ok) throw new Error(`Webhook ${origin(options.url)} answered ${response.status}`);
|
|
26
25
|
}
|
|
27
26
|
};
|
|
28
27
|
}
|
|
28
|
+
async function hmacSha256Hex(secret, body) {
|
|
29
|
+
const encoder = new TextEncoder();
|
|
30
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
31
|
+
const signature = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(body)));
|
|
32
|
+
return Array.from(signature, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
33
|
+
}
|
|
29
34
|
|
|
35
|
+
exports.hmacSha256Hex = hmacSha256Hex;
|
|
30
36
|
exports.webhook = webhook;
|
|
31
37
|
//# sourceMappingURL=webhook.cjs.map
|
|
32
38
|
//# sourceMappingURL=webhook.cjs.map
|
package/dist/webhook.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/alerts/webhook.ts"],"names":[
|
|
1
|
+
{"version":3,"sources":["../src/alerts/webhook.ts"],"names":[],"mappings":";;;AAcA,IAAM,UAAA,GAAa,GAAA;AAEnB,SAAS,OAAO,GAAA,EAAqB;AACnC,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,MAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,eAAA;AAAA,EACT;AACF;AAOO,SAAS,QAAQ,OAAA,EAAuC;AAC7D,EAAA,IAAI,CAAC,OAAA,CAAQ,GA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AO,MAAM,GAAG,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAM,SAAA,IAAa,KAAA,EAAO,CAAC,MAAM,CAAC,CAAA;AAC3H,EAAA,MAAM,SAAA,GAAY,IAAI,UAAA,CAAW,MAAM,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,MAAA,EAAQ,GAAA,EAAK,OAAA,CAAQ,MAAA,CAAO,IAAI,CAAC,CAAC,CAAA;AAC5F,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,SAAA,EAAW,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC9E","file":"webhook.cjs","sourcesContent":["import type { AlertChannel } from \"../types.js\";\n\nexport interface WebhookOptions {\n url: string;\n /** Extra request headers, for an Authorization header say. Values are trimmed. */\n headers?: Record<string, string>;\n /**\n * When set, each request carries `X-CronWatch-Signature: sha256=<hex>`,\n * the HMAC-SHA256 of the raw body with this secret, so the receiver can\n * verify it.\n */\n secret?: string;\n}\n\nconst TIMEOUT_MS = 10_000;\n\nfunction origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/**\n * POSTs the alert as JSON to any URL. The body is the Alert object:\n * { type, job, title, message, run, details, triage, at, definition }.\n * A redirect is an error: point the url at where the receiver really is.\n */\nexport function webhook(options: WebhookOptions): AlertChannel {\n if (!options.url) throw new Error(\"webhook() needs a url\");\n return {\n name: \"webhook\",\n async send(alert) {\n const body = JSON.stringify(alert);\n const headers: Record<string, string> = { \"content-type\": \"application/json\", \"user-agent\": \"cronwatch\" };\n // A pasted Authorization value often carries a stray space or newline, which fetch would refuse.\n for (const [name, value] of Object.entries(options.headers ?? {})) headers[name] = typeof value === \"string\" ? value.trim() : value;\n if (options.secret) {\n headers[\"x-cronwatch-signature\"] = `sha256=${await hmacSha256Hex(options.secret, body)}`;\n }\n // A redirect is refused, not followed: the headers (and the signature) would go with it.\n const response = await fetch(options.url, { method: \"POST\", headers, body, redirect: \"error\", signal: AbortSignal.timeout(TIMEOUT_MS) });\n // Only the origin: a webhook URL's path or query often is the credential.\n if (!response.ok) throw new Error(`Webhook ${origin(options.url)} answered ${response.status}`);\n },\n };\n}\n\n/** HMAC-SHA256 as lowercase hex, with Web Crypto so it runs on Workers and Deno too. */\nexport async function hmacSha256Hex(secret: string, body: string): Promise<string> {\n const encoder = new TextEncoder();\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n const signature = new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(body)));\n return Array.from(signature, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n"]}
|
package/dist/webhook.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { a as AlertChannel } from './types-
|
|
1
|
+
import { a as AlertChannel } from './types-Ddq1MUPL.cjs';
|
|
2
2
|
|
|
3
3
|
interface WebhookOptions {
|
|
4
4
|
url: string;
|
|
5
|
-
/** Extra request headers, for an Authorization header say. */
|
|
5
|
+
/** Extra request headers, for an Authorization header say. Values are trimmed. */
|
|
6
6
|
headers?: Record<string, string>;
|
|
7
7
|
/**
|
|
8
8
|
* When set, each request carries `X-CronWatch-Signature: sha256=<hex>`,
|
|
@@ -14,7 +14,10 @@ interface WebhookOptions {
|
|
|
14
14
|
/**
|
|
15
15
|
* POSTs the alert as JSON to any URL. The body is the Alert object:
|
|
16
16
|
* { type, job, title, message, run, details, triage, at, definition }.
|
|
17
|
+
* A redirect is an error: point the url at where the receiver really is.
|
|
17
18
|
*/
|
|
18
19
|
declare function webhook(options: WebhookOptions): AlertChannel;
|
|
20
|
+
/** HMAC-SHA256 as lowercase hex, with Web Crypto so it runs on Workers and Deno too. */
|
|
21
|
+
declare function hmacSha256Hex(secret: string, body: string): Promise<string>;
|
|
19
22
|
|
|
20
|
-
export { type WebhookOptions, webhook };
|
|
23
|
+
export { type WebhookOptions, hmacSha256Hex, webhook };
|
package/dist/webhook.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { a as AlertChannel } from './types-
|
|
1
|
+
import { a as AlertChannel } from './types-Ddq1MUPL.js';
|
|
2
2
|
|
|
3
3
|
interface WebhookOptions {
|
|
4
4
|
url: string;
|
|
5
|
-
/** Extra request headers, for an Authorization header say. */
|
|
5
|
+
/** Extra request headers, for an Authorization header say. Values are trimmed. */
|
|
6
6
|
headers?: Record<string, string>;
|
|
7
7
|
/**
|
|
8
8
|
* When set, each request carries `X-CronWatch-Signature: sha256=<hex>`,
|
|
@@ -14,7 +14,10 @@ interface WebhookOptions {
|
|
|
14
14
|
/**
|
|
15
15
|
* POSTs the alert as JSON to any URL. The body is the Alert object:
|
|
16
16
|
* { type, job, title, message, run, details, triage, at, definition }.
|
|
17
|
+
* A redirect is an error: point the url at where the receiver really is.
|
|
17
18
|
*/
|
|
18
19
|
declare function webhook(options: WebhookOptions): AlertChannel;
|
|
20
|
+
/** HMAC-SHA256 as lowercase hex, with Web Crypto so it runs on Workers and Deno too. */
|
|
21
|
+
declare function hmacSha256Hex(secret: string, body: string): Promise<string>;
|
|
19
22
|
|
|
20
|
-
export { type WebhookOptions, webhook };
|
|
23
|
+
export { type WebhookOptions, hmacSha256Hex, webhook };
|
package/dist/webhook.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { createHmac } from 'crypto';
|
|
2
|
-
|
|
3
1
|
// src/alerts/webhook.ts
|
|
4
2
|
var TIMEOUT_MS = 1e4;
|
|
5
3
|
function origin(url) {
|
|
@@ -15,16 +13,23 @@ function webhook(options) {
|
|
|
15
13
|
name: "webhook",
|
|
16
14
|
async send(alert) {
|
|
17
15
|
const body = JSON.stringify(alert);
|
|
18
|
-
const headers = { "content-type": "application/json", "user-agent": "cronwatch"
|
|
16
|
+
const headers = { "content-type": "application/json", "user-agent": "cronwatch" };
|
|
17
|
+
for (const [name, value] of Object.entries(options.headers ?? {})) headers[name] = typeof value === "string" ? value.trim() : value;
|
|
19
18
|
if (options.secret) {
|
|
20
|
-
headers["x-cronwatch-signature"] = `sha256=${
|
|
19
|
+
headers["x-cronwatch-signature"] = `sha256=${await hmacSha256Hex(options.secret, body)}`;
|
|
21
20
|
}
|
|
22
|
-
const response = await fetch(options.url, { method: "POST", headers, body, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
21
|
+
const response = await fetch(options.url, { method: "POST", headers, body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
23
22
|
if (!response.ok) throw new Error(`Webhook ${origin(options.url)} answered ${response.status}`);
|
|
24
23
|
}
|
|
25
24
|
};
|
|
26
25
|
}
|
|
26
|
+
async function hmacSha256Hex(secret, body) {
|
|
27
|
+
const encoder = new TextEncoder();
|
|
28
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
29
|
+
const signature = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(body)));
|
|
30
|
+
return Array.from(signature, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
31
|
+
}
|
|
27
32
|
|
|
28
|
-
export { webhook };
|
|
33
|
+
export { hmacSha256Hex, webhook };
|
|
29
34
|
//# sourceMappingURL=webhook.js.map
|
|
30
35
|
//# sourceMappingURL=webhook.js.map
|
package/dist/webhook.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/alerts/webhook.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/alerts/webhook.ts"],"names":[],"mappings":";AAcA,IAAM,UAAA,GAAa,GAAA;AAEnB,SAAS,OAAO,GAAA,EAAqB;AACnC,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,MAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO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A,EAAY;AAChC,EAAA,MAAM,MAAM,MAAM,MAAA,CAAO,OAAO,SAAA,CAAU,KAAA,EAAO,QAAQ,MAAA,CAAO,MAAM,GAAG,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAM,SAAA,IAAa,KAAA,EAAO,CAAC,MAAM,CAAC,CAAA;AAC3H,EAAA,MAAM,SAAA,GAAY,IAAI,UAAA,CAAW,MAAM,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,MAAA,EAAQ,GAAA,EAAK,OAAA,CAAQ,MAAA,CAAO,IAAI,CAAC,CAAC,CAAA;AAC5F,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,SAAA,EAAW,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC9E","file":"webhook.js","sourcesContent":["import type { AlertChannel } from \"../types.js\";\n\nexport interface WebhookOptions {\n url: string;\n /** Extra request headers, for an Authorization header say. Values are trimmed. */\n headers?: Record<string, string>;\n /**\n * When set, each request carries `X-CronWatch-Signature: sha256=<hex>`,\n * the HMAC-SHA256 of the raw body with this secret, so the receiver can\n * verify it.\n */\n secret?: string;\n}\n\nconst TIMEOUT_MS = 10_000;\n\nfunction origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/**\n * POSTs the alert as JSON to any URL. The body is the Alert object:\n * { type, job, title, message, run, details, triage, at, definition }.\n * A redirect is an error: point the url at where the receiver really is.\n */\nexport function webhook(options: WebhookOptions): AlertChannel {\n if (!options.url) throw new Error(\"webhook() needs a url\");\n return {\n name: \"webhook\",\n async send(alert) {\n const body = JSON.stringify(alert);\n const headers: Record<string, string> = { \"content-type\": \"application/json\", \"user-agent\": \"cronwatch\" };\n // A pasted Authorization value often carries a stray space or newline, which fetch would refuse.\n for (const [name, value] of Object.entries(options.headers ?? {})) headers[name] = typeof value === \"string\" ? value.trim() : value;\n if (options.secret) {\n headers[\"x-cronwatch-signature\"] = `sha256=${await hmacSha256Hex(options.secret, body)}`;\n }\n // A redirect is refused, not followed: the headers (and the signature) would go with it.\n const response = await fetch(options.url, { method: \"POST\", headers, body, redirect: \"error\", signal: AbortSignal.timeout(TIMEOUT_MS) });\n // Only the origin: a webhook URL's path or query often is the credential.\n if (!response.ok) throw new Error(`Webhook ${origin(options.url)} answered ${response.status}`);\n },\n };\n}\n\n/** HMAC-SHA256 as lowercase hex, with Web Crypto so it runs on Workers and Deno too. */\nexport async function hmacSha256Hex(secret: string, body: string): Promise<string> {\n const encoder = new TextEncoder();\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n const signature = new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(body)));\n return Array.from(signature, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n"]}
|