@cronwatch/sdk 0.12.4 → 0.13.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 +3 -3
- package/dist/anthropic.cjs +2 -2
- package/dist/anthropic.cjs.map +1 -1
- package/dist/anthropic.d.cts +1 -1
- package/dist/anthropic.d.ts +1 -1
- package/dist/anthropic.js +2 -2
- package/dist/anthropic.js.map +1 -1
- package/dist/bugsnag.cjs +7 -0
- package/dist/bugsnag.cjs.map +1 -1
- package/dist/bugsnag.d.cts +1 -1
- package/dist/bugsnag.d.ts +1 -1
- package/dist/bugsnag.js +7 -0
- package/dist/bugsnag.js.map +1 -1
- package/dist/{client-BkPMRkDq.d.cts → client-DAJH7YiG.d.ts} +41 -20
- package/dist/{client-DySsV5T0.d.ts → client-z1LdR_m2.d.cts} +41 -20
- package/dist/d1.cjs +1 -1
- package/dist/d1.cjs.map +1 -1
- package/dist/d1.d.cts +4 -4
- package/dist/d1.d.ts +4 -4
- package/dist/d1.js +1 -1
- package/dist/d1.js.map +1 -1
- package/dist/datadog.cjs +7 -0
- package/dist/datadog.cjs.map +1 -1
- package/dist/datadog.d.cts +2 -2
- package/dist/datadog.d.ts +2 -2
- package/dist/datadog.js +7 -0
- package/dist/datadog.js.map +1 -1
- package/dist/discord.cjs +25 -1
- package/dist/discord.cjs.map +1 -1
- package/dist/discord.d.cts +5 -5
- package/dist/discord.d.ts +5 -5
- package/dist/discord.js +25 -1
- package/dist/discord.js.map +1 -1
- package/dist/{email-CD6NO8CV.d.cts → email-CCUzlLe9.d.cts} +3 -3
- package/dist/{email-Bx3ehK0O.d.ts → email-CFtDqlvZ.d.ts} +3 -3
- package/dist/honeybadger.cjs +7 -0
- package/dist/honeybadger.cjs.map +1 -1
- package/dist/honeybadger.d.cts +1 -1
- package/dist/honeybadger.d.ts +1 -1
- package/dist/honeybadger.js +7 -0
- package/dist/honeybadger.js.map +1 -1
- package/dist/index.cjs +206 -58
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +206 -58
- package/dist/index.js.map +1 -1
- package/dist/mailgun.cjs +7 -0
- package/dist/mailgun.cjs.map +1 -1
- package/dist/mailgun.d.cts +2 -2
- package/dist/mailgun.d.ts +2 -2
- package/dist/mailgun.js +7 -0
- package/dist/mailgun.js.map +1 -1
- package/dist/newrelic.cjs +7 -0
- package/dist/newrelic.cjs.map +1 -1
- package/dist/newrelic.d.cts +1 -1
- package/dist/newrelic.d.ts +1 -1
- package/dist/newrelic.js +7 -0
- package/dist/newrelic.js.map +1 -1
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +3 -3
- package/dist/node.d.ts +3 -3
- package/dist/node.js.map +1 -1
- package/dist/pg-cron.cjs.map +1 -1
- package/dist/pg-cron.d.cts +10 -10
- package/dist/pg-cron.d.ts +10 -10
- package/dist/pg-cron.js.map +1 -1
- package/dist/postgres.cjs +8 -3
- package/dist/postgres.cjs.map +1 -1
- package/dist/postgres.d.cts +3 -3
- package/dist/postgres.d.ts +3 -3
- package/dist/postgres.js +8 -3
- package/dist/postgres.js.map +1 -1
- package/dist/postmark.cjs +7 -0
- package/dist/postmark.cjs.map +1 -1
- package/dist/postmark.d.cts +2 -2
- package/dist/postmark.d.ts +2 -2
- package/dist/postmark.js +7 -0
- package/dist/postmark.js.map +1 -1
- package/dist/resend.cjs +7 -0
- package/dist/resend.cjs.map +1 -1
- package/dist/resend.d.cts +2 -2
- package/dist/resend.d.ts +2 -2
- package/dist/resend.js +7 -0
- package/dist/resend.js.map +1 -1
- package/dist/rollbar.cjs +7 -0
- package/dist/rollbar.cjs.map +1 -1
- package/dist/rollbar.d.cts +1 -1
- package/dist/rollbar.d.ts +1 -1
- package/dist/rollbar.js +7 -0
- package/dist/rollbar.js.map +1 -1
- package/dist/sendgrid.cjs +7 -0
- package/dist/sendgrid.cjs.map +1 -1
- package/dist/sendgrid.d.cts +2 -2
- package/dist/sendgrid.d.ts +2 -2
- package/dist/sendgrid.js +7 -0
- package/dist/sendgrid.js.map +1 -1
- package/dist/sentry.cjs +7 -0
- package/dist/sentry.cjs.map +1 -1
- package/dist/sentry.d.cts +2 -2
- package/dist/sentry.d.ts +2 -2
- package/dist/sentry.js +7 -0
- package/dist/sentry.js.map +1 -1
- package/dist/ses.cjs +7 -0
- package/dist/ses.cjs.map +1 -1
- package/dist/ses.d.cts +2 -2
- package/dist/ses.d.ts +2 -2
- package/dist/ses.js +7 -0
- package/dist/ses.js.map +1 -1
- package/dist/slack.cjs +32 -1
- 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 +32 -1
- package/dist/slack.js.map +1 -1
- package/dist/sqlite.cjs +1 -1
- package/dist/sqlite.cjs.map +1 -1
- package/dist/sqlite.d.cts +2 -2
- package/dist/sqlite.d.ts +2 -2
- package/dist/sqlite.js +1 -1
- package/dist/sqlite.js.map +1 -1
- package/dist/twilio.cjs +7 -0
- package/dist/twilio.cjs.map +1 -1
- package/dist/twilio.d.cts +5 -5
- package/dist/twilio.d.ts +5 -5
- package/dist/twilio.js +7 -0
- package/dist/twilio.js.map +1 -1
- package/dist/{types-Bm972Uqj.d.cts → types-D6t0Z846.d.cts} +15 -7
- package/dist/{types-Bm972Uqj.d.ts → types-D6t0Z846.d.ts} +15 -7
- package/dist/webhook.cjs +11 -1
- package/dist/webhook.cjs.map +1 -1
- package/dist/webhook.d.cts +4 -3
- package/dist/webhook.d.ts +4 -3
- package/dist/webhook.js +11 -1
- package/dist/webhook.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Everything public about a job, a run and an alert. Kept in one file so the
|
|
2
|
+
* Everything public about a job, a run, and an alert. Kept in one file so the
|
|
3
3
|
* store and alert adapters, which are built as separate entry points, share
|
|
4
4
|
* one definition.
|
|
5
5
|
*/
|
|
@@ -10,7 +10,7 @@ interface JobOptions {
|
|
|
10
10
|
/**
|
|
11
11
|
* When the job is supposed to run. A five or six field cron expression
|
|
12
12
|
* ("0 2 * * *"), a cron nickname ("@hourly"), or an interval ("every 5m").
|
|
13
|
-
* Leave it out for a job that has no fixed cadence: failures, duration and
|
|
13
|
+
* Leave it out for a job that has no fixed cadence: failures, duration, and
|
|
14
14
|
* budgets are still watched, but nothing is ever reported as missed.
|
|
15
15
|
*/
|
|
16
16
|
schedule?: string;
|
|
@@ -87,7 +87,7 @@ interface Run {
|
|
|
87
87
|
metrics: Record<string, number>;
|
|
88
88
|
/**
|
|
89
89
|
* What started the run: "run", "start", "handler", an integration's name
|
|
90
|
-
* ("pg_cron" for the pg_cron source) or a value you pass.
|
|
90
|
+
* ("pg_cron" for the pg_cron source), or a value you pass.
|
|
91
91
|
*/
|
|
92
92
|
trigger: string;
|
|
93
93
|
}
|
|
@@ -122,6 +122,14 @@ interface JobState {
|
|
|
122
122
|
* existed.
|
|
123
123
|
*/
|
|
124
124
|
underFloor?: string[];
|
|
125
|
+
/**
|
|
126
|
+
* The ids of runs started and not yet judged, oldest first (see
|
|
127
|
+
* holdRun). A run leaves when its finish is evaluated; one a check finds
|
|
128
|
+
* finished and still here (the process that finished it stopped before
|
|
129
|
+
* writing its evaluation) is evaluated by that check. Absent when empty,
|
|
130
|
+
* and in state written before this field existed.
|
|
131
|
+
*/
|
|
132
|
+
pendingRuns?: string[];
|
|
125
133
|
/**
|
|
126
134
|
* Goes up by one on every write, so a store can refuse a write made from a
|
|
127
135
|
* stale read (see Store.compareAndSetState). Absent counts as 0.
|
|
@@ -193,7 +201,7 @@ interface AlertBase {
|
|
|
193
201
|
message: string;
|
|
194
202
|
/**
|
|
195
203
|
* A short diagnosis from the triage function, when one is configured. Null
|
|
196
|
-
* when triage was tried and gave nothing (it threw, timed out or answered
|
|
204
|
+
* when triage was tried and gave nothing (it threw, timed out, or answered
|
|
197
205
|
* empty); it is not tried again for this alert.
|
|
198
206
|
*/
|
|
199
207
|
triage?: string | null;
|
|
@@ -225,9 +233,9 @@ interface AlertChannel {
|
|
|
225
233
|
send(alert: Alert, context?: ChannelContext): Promise<void>;
|
|
226
234
|
}
|
|
227
235
|
/**
|
|
228
|
-
* Where jobs, runs and state are kept. A store holds text without U+0000,
|
|
236
|
+
* Where jobs, runs, and state are kept. A store holds text without U+0000,
|
|
229
237
|
* which Postgres refuses: it drops every NUL from a run's trigger, output,
|
|
230
|
-
* error and metric names, and from every key and string of a definition and
|
|
238
|
+
* error, and metric names, and from every key and string of a definition and
|
|
231
239
|
* a state, as it writes them. Job names and run ids never hold one.
|
|
232
240
|
*/
|
|
233
241
|
interface Store {
|
|
@@ -240,7 +248,7 @@ interface Store {
|
|
|
240
248
|
insertRun(run: Run): Promise<void>;
|
|
241
249
|
updateRun(run: Run): Promise<void>;
|
|
242
250
|
/**
|
|
243
|
-
* Write a run's status, finishedAt, durationMs, error, output and metrics
|
|
251
|
+
* Write a run's status, finishedAt, durationMs, error, output, and metrics
|
|
244
252
|
* only when its stored status is one of `fromStatuses`, in one step (SQL:
|
|
245
253
|
* `UPDATE ... WHERE id = ? AND status IN (...)`). Returns whether it wrote.
|
|
246
254
|
* This is what lets exactly one of several processes finishing the same run
|
package/dist/webhook.cjs
CHANGED
|
@@ -11,6 +11,12 @@ function postable(url) {
|
|
|
11
11
|
if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
|
|
12
12
|
return url;
|
|
13
13
|
}
|
|
14
|
+
async function drain(response) {
|
|
15
|
+
try {
|
|
16
|
+
await response.body?.cancel();
|
|
17
|
+
} catch {
|
|
18
|
+
}
|
|
19
|
+
}
|
|
14
20
|
|
|
15
21
|
// src/alerts/webhook.ts
|
|
16
22
|
var TIMEOUT_MS = 1e4;
|
|
@@ -26,8 +32,11 @@ function webhook(options) {
|
|
|
26
32
|
if (!options.url) throw new Error("webhook() needs a url");
|
|
27
33
|
return {
|
|
28
34
|
name: "webhook",
|
|
29
|
-
async send(alert) {
|
|
35
|
+
async send(alert, context) {
|
|
30
36
|
const body = JSON.stringify({ schema: WEBHOOK_SCHEMA, ...alert });
|
|
37
|
+
if (options.secret === "") {
|
|
38
|
+
context?.onError?.(new Error("webhook: secret is an empty string, so this request is sent unsigned; set the secret, or leave it out to send unsigned on purpose"));
|
|
39
|
+
}
|
|
31
40
|
const headers = { "content-type": "application/json", "user-agent": "cronwatch" };
|
|
32
41
|
for (const [name, value] of Object.entries(options.headers ?? {})) headers[name] = typeof value === "string" ? value.trim() : value;
|
|
33
42
|
if (options.secret) {
|
|
@@ -35,6 +44,7 @@ function webhook(options) {
|
|
|
35
44
|
}
|
|
36
45
|
const response = await fetch(postable(options.url), { method: "POST", headers, body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
37
46
|
if (!response.ok) throw new Error(`Webhook ${origin(options.url)} answered ${response.status}`);
|
|
47
|
+
await drain(response);
|
|
38
48
|
}
|
|
39
49
|
};
|
|
40
50
|
}
|
package/dist/webhook.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/webhook.ts","../src/entries/webhook.ts"],"names":["signature"],"mappings":";;;AAiCO,SAAS,SAAS,GAAA,EAAqB;AAC5C,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI;AACF,IAAA,QAAA,GAAW,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,QAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,MAAM,yDAAyD,CAAA;AAAA,EAC3E;AACA,EAAA,IAAI,QAAA,KAAa,WAAW,QAAA,KAAa,QAAA,QAAgB,IAAI,KAAA,CAAM,CAAA,+CAAA,EAAkD,QAAQ,CAAA,CAAE,CAAA;AAC/H,EAAA,OAAO,GAAA;AACT;;;AC3BA,IAAM,UAAA,GAAa,GAAA;AAOZ,IAAM,cAAA,GAAiB,CAAA;AAE9B,SAAS,OAAO,GAAA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AAA,EAAa,QAAA,CAAS,MAAM,CAAA,CAAE,CAAA;AAAA,IAChG;AAAA,GACF;AACF;AAUA,eAAsB,SAAA,CAAU,QAAgB,IAAA,EAA+B;AAC7E,EAAA,MAAM,OAAA,GAAU,IAAI,WAAA,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,MAAMA,UAAAA,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,CAAKA,UAAAA,EAAW,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC9E;;;AC/DO,IAAM,aAAA,GAAyB","file":"webhook.cjs","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 { isoTime } from \"../duration.js\";\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\" || type === \"under_floor\") 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/**\n * The URL, once it is one fetch can post to. Refused without quoting it:\n * fetch's own error for a URL it cannot parse (\"Failed to parse URL from ...\")\n * quotes the whole URL, and a webhook URL's path is its credential.\n */\nexport function postable(url: string): string {\n let protocol: string;\n try {\n protocol = new URL(url).protocol;\n } catch {\n throw new Error(\"only http and https URLs can be posted to, not this URL\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);\n return url;\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(postable(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. A start before the year 1 or after 9999 is null. */\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: isoTime(run.startedAt), 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","import type { AlertChannel } from \"../types.js\";\nimport { postable } from \"./shared.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\n/**\n * The payload's version, sent as its first field. It goes up only if a\n * major release changes the payload in a way that is not additive; see\n * https://cronwatch.dev/schemas/webhook/1.json.\n */\nexport const WEBHOOK_SCHEMA = 1;\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 after a\n * version: { schema: 1, type, job, title, message, run, details, triage, at,\n * definition }. A redirect is an error: point the url at where the receiver\n * 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({ schema: WEBHOOK_SCHEMA, ...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 signature(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(postable(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/**\n * The webhook's signature of a body: the HMAC-SHA256 of the body with the\n * secret, as lowercase hex. A request carries it as\n * `X-CronWatch-Signature: sha256=<signature>`, so a receiver checks one with\n * the raw body it got (before any JSON parsing) and a constant-time compare.\n * Web Crypto, so it runs on Workers and Deno too. Every port has it, named\n * the same.\n */\nexport async function signature(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","// @cronwatch/sdk/webhook: the channel, and signature(), the one helper for\n// a receiver, named the same in every port.\nimport * as internal from \"../alerts/webhook.js\";\n\nexport { signature, webhook } from \"../alerts/webhook.js\";\nexport type { WebhookOptions } from \"../alerts/webhook.js\";\n\n/** @deprecated Renamed `signature`, the name every port uses; this name is no longer exported from 1.0. */\nexport const hmacSha256Hex = internal.signature;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/webhook.ts","../src/entries/webhook.ts"],"names":["signature"],"mappings":";;;AAiCO,SAAS,SAAS,GAAA,EAAqB;AAC5C,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI;AACF,IAAA,QAAA,GAAW,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,QAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,MAAM,yDAAyD,CAAA;AAAA,EAC3E;AACA,EAAA,IAAI,QAAA,KAAa,WAAW,QAAA,KAAa,QAAA,QAAgB,IAAI,KAAA,CAAM,CAAA,+CAAA,EAAkD,QAAQ,CAAA,CAAE,CAAA;AAC/H,EAAA,OAAO,GAAA;AACT;AAiCA,eAAsB,MAAM,QAAA,EAAmC;AAC7D,EAAA,IAAI;AACF,IAAA,MAAM,QAAA,CAAS,MAAM,MAAA,EAAO;AAAA,EAC9B,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;;;ACjEA,IAAM,UAAA,GAAa,GAAA;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AM,UAAU,OAAA,EAAS,MAAA,EAAQ,YAAY,OAAA,CAAQ,UAAU,GAAG,CAAA;AAEjJ,MAAA,IAAI,CAAC,QAAA,CAAS,EAAA,EAAI,MAAM,IAAI,KAAA,CAAM,CAAA,QAAA,EAAW,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAC,CAAA,UAAA,EAAa,QAAA,CAAS,MAAM,CAAA,CAAE,CAAA;AAC9F,MAAA,MAAM,MAAM,QAAQ,CAAA;AAAA,IACtB;AAAA,GACF;AACF;AAUA,eAAsB,SAAA,CAAU,QAAgB,IAAA,EAA+B;AAC7E,EAAA,MAAM,OAAA,GAAU,IAAI,WAAA,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,MAAMA,UAAAA,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,CAAKA,UAAAA,EAAW,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC9E;;;ACpEO,IAAM,aAAA,GAAyB","file":"webhook.cjs","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 { isoTime } from \"../duration.js\";\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\" || type === \"under_floor\") 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/**\n * The URL, once it is one fetch can post to. Refused without quoting it:\n * fetch's own error for a URL it cannot parse (\"Failed to parse URL from ...\")\n * quotes the whole URL, and a webhook URL's path is its credential.\n */\nexport function postable(url: string): string {\n let protocol: string;\n try {\n protocol = new URL(url).protocol;\n } catch {\n throw new Error(\"only http and https URLs can be posted to, not this URL\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);\n return url;\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(postable(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 await drain(response);\n return response;\n}\n\n/**\n * Lets go of a successful answer's body, which nothing reads, so its\n * connection goes back to the pool now rather than when it is collected.\n */\nexport async function drain(response: Response): Promise<void> {\n try {\n await response.body?.cancel();\n } catch {\n // Already read, or the connection is gone: nothing to let go of.\n }\n}\n\n/**\n * The parts of a webhook URL that are its credential, to cut from an error\n * body that echoes the request: its path and query together, then the last\n * segment of its path (Slack's and Discord's token) on its own.\n */\nexport function urlSecrets(url: string): string[] {\n try {\n const parsed = new URL(url);\n const last = parsed.pathname.split(\"/\").pop() ?? \"\";\n return [parsed.pathname + parsed.search, last].filter((part) => part.length > 0 && part !== \"/\");\n } catch {\n return [];\n }\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. A start before the year 1 or after 9999 is null. */\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: isoTime(run.startedAt), 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","import type { AlertChannel } from \"../types.js\";\nimport { drain, postable } from \"./shared.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. An empty string (an unset variable read as \"\", say) signs\n * nothing, and each send reports that to onError.\n */\n secret?: string;\n}\n\nconst TIMEOUT_MS = 10_000;\n\n/**\n * The payload's version, sent as its first field. It goes up only if a\n * major release changes the payload in a way that is not additive; see\n * https://cronwatch.dev/schemas/webhook/1.json.\n */\nexport const WEBHOOK_SCHEMA = 1;\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 after a\n * version: { schema: 1, type, job, title, message, run, details, triage, at,\n * definition }. A redirect is an error: point the url at where the receiver\n * 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, context) {\n const body = JSON.stringify({ schema: WEBHOOK_SCHEMA, ...alert });\n if (options.secret === \"\") {\n context?.onError?.(new Error(\"webhook: secret is an empty string, so this request is sent unsigned; set the secret, or leave it out to send unsigned on purpose\"));\n }\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 signature(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(postable(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 await drain(response);\n },\n };\n}\n\n/**\n * The webhook's signature of a body: the HMAC-SHA256 of the body with the\n * secret, as lowercase hex. A request carries it as\n * `X-CronWatch-Signature: sha256=<signature>`, so a receiver checks one with\n * the raw body it got (before any JSON parsing) and a constant-time compare.\n * Web Crypto, so it runs on Workers and Deno too. Every port has it, named\n * the same.\n */\nexport async function signature(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","// @cronwatch/sdk/webhook: the channel, and signature(), the one helper for\n// a receiver, named the same in every port.\nimport * as internal from \"../alerts/webhook.js\";\n\nexport { signature, webhook } from \"../alerts/webhook.js\";\nexport type { WebhookOptions } from \"../alerts/webhook.js\";\n\n/** @deprecated Renamed `signature`, the name every port uses; this name leaves the exports in 1.0. */\nexport const hmacSha256Hex = internal.signature;\n"]}
|
package/dist/webhook.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as AlertChannel } from './types-
|
|
1
|
+
import { a as AlertChannel } from './types-D6t0Z846.cjs';
|
|
2
2
|
|
|
3
3
|
interface WebhookOptions {
|
|
4
4
|
url: string;
|
|
@@ -7,7 +7,8 @@ interface WebhookOptions {
|
|
|
7
7
|
/**
|
|
8
8
|
* When set, each request carries `X-CronWatch-Signature: sha256=<hex>`,
|
|
9
9
|
* the HMAC-SHA256 of the raw body with this secret, so the receiver can
|
|
10
|
-
* verify it.
|
|
10
|
+
* verify it. An empty string (an unset variable read as "", say) signs
|
|
11
|
+
* nothing, and each send reports that to onError.
|
|
11
12
|
*/
|
|
12
13
|
secret?: string;
|
|
13
14
|
}
|
|
@@ -28,7 +29,7 @@ declare function webhook(options: WebhookOptions): AlertChannel;
|
|
|
28
29
|
*/
|
|
29
30
|
declare function signature(secret: string, body: string): Promise<string>;
|
|
30
31
|
|
|
31
|
-
/** @deprecated Renamed `signature`, the name every port uses; this name
|
|
32
|
+
/** @deprecated Renamed `signature`, the name every port uses; this name leaves the exports in 1.0. */
|
|
32
33
|
declare const hmacSha256Hex: typeof signature;
|
|
33
34
|
|
|
34
35
|
export { type WebhookOptions, hmacSha256Hex, signature, webhook };
|
package/dist/webhook.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as AlertChannel } from './types-
|
|
1
|
+
import { a as AlertChannel } from './types-D6t0Z846.js';
|
|
2
2
|
|
|
3
3
|
interface WebhookOptions {
|
|
4
4
|
url: string;
|
|
@@ -7,7 +7,8 @@ interface WebhookOptions {
|
|
|
7
7
|
/**
|
|
8
8
|
* When set, each request carries `X-CronWatch-Signature: sha256=<hex>`,
|
|
9
9
|
* the HMAC-SHA256 of the raw body with this secret, so the receiver can
|
|
10
|
-
* verify it.
|
|
10
|
+
* verify it. An empty string (an unset variable read as "", say) signs
|
|
11
|
+
* nothing, and each send reports that to onError.
|
|
11
12
|
*/
|
|
12
13
|
secret?: string;
|
|
13
14
|
}
|
|
@@ -28,7 +29,7 @@ declare function webhook(options: WebhookOptions): AlertChannel;
|
|
|
28
29
|
*/
|
|
29
30
|
declare function signature(secret: string, body: string): Promise<string>;
|
|
30
31
|
|
|
31
|
-
/** @deprecated Renamed `signature`, the name every port uses; this name
|
|
32
|
+
/** @deprecated Renamed `signature`, the name every port uses; this name leaves the exports in 1.0. */
|
|
32
33
|
declare const hmacSha256Hex: typeof signature;
|
|
33
34
|
|
|
34
35
|
export { type WebhookOptions, hmacSha256Hex, signature, webhook };
|
package/dist/webhook.js
CHANGED
|
@@ -9,6 +9,12 @@ function postable(url) {
|
|
|
9
9
|
if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
|
|
10
10
|
return url;
|
|
11
11
|
}
|
|
12
|
+
async function drain(response) {
|
|
13
|
+
try {
|
|
14
|
+
await response.body?.cancel();
|
|
15
|
+
} catch {
|
|
16
|
+
}
|
|
17
|
+
}
|
|
12
18
|
|
|
13
19
|
// src/alerts/webhook.ts
|
|
14
20
|
var TIMEOUT_MS = 1e4;
|
|
@@ -24,8 +30,11 @@ function webhook(options) {
|
|
|
24
30
|
if (!options.url) throw new Error("webhook() needs a url");
|
|
25
31
|
return {
|
|
26
32
|
name: "webhook",
|
|
27
|
-
async send(alert) {
|
|
33
|
+
async send(alert, context) {
|
|
28
34
|
const body = JSON.stringify({ schema: WEBHOOK_SCHEMA, ...alert });
|
|
35
|
+
if (options.secret === "") {
|
|
36
|
+
context?.onError?.(new Error("webhook: secret is an empty string, so this request is sent unsigned; set the secret, or leave it out to send unsigned on purpose"));
|
|
37
|
+
}
|
|
29
38
|
const headers = { "content-type": "application/json", "user-agent": "cronwatch" };
|
|
30
39
|
for (const [name, value] of Object.entries(options.headers ?? {})) headers[name] = typeof value === "string" ? value.trim() : value;
|
|
31
40
|
if (options.secret) {
|
|
@@ -33,6 +42,7 @@ function webhook(options) {
|
|
|
33
42
|
}
|
|
34
43
|
const response = await fetch(postable(options.url), { method: "POST", headers, body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
35
44
|
if (!response.ok) throw new Error(`Webhook ${origin(options.url)} answered ${response.status}`);
|
|
45
|
+
await drain(response);
|
|
36
46
|
}
|
|
37
47
|
};
|
|
38
48
|
}
|
package/dist/webhook.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/webhook.ts","../src/entries/webhook.ts"],"names":["signature"],"mappings":";AAiCO,SAAS,SAAS,GAAA,EAAqB;AAC5C,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI;AACF,IAAA,QAAA,GAAW,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,QAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,MAAM,yDAAyD,CAAA;AAAA,EAC3E;AACA,EAAA,IAAI,QAAA,KAAa,WAAW,QAAA,KAAa,QAAA,QAAgB,IAAI,KAAA,CAAM,CAAA,+CAAA,EAAkD,QAAQ,CAAA,CAAE,CAAA;AAC/H,EAAA,OAAO,GAAA;AACT;;;AC3BA,IAAM,UAAA,GAAa,GAAA;AAOZ,IAAM,cAAA,GAAiB,CAAA;AAE9B,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;AAQO,SAAS,QAAQ,OAAA,EAAuC;AAC7D,EAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,EAAK,MAAM,I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Q,MAAA,CAAO,MAAM,GAAG,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAM,SAAA,IAAa,KAAA,EAAO,CAAC,MAAM,CAAC,CAAA;AAC3H,EAAA,MAAMA,UAAAA,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,CAAKA,UAAAA,EAAW,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC9E;;;AC/DO,IAAM,aAAA,GAAyB","file":"webhook.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 { isoTime } from \"../duration.js\";\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\" || type === \"under_floor\") 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/**\n * The URL, once it is one fetch can post to. Refused without quoting it:\n * fetch's own error for a URL it cannot parse (\"Failed to parse URL from ...\")\n * quotes the whole URL, and a webhook URL's path is its credential.\n */\nexport function postable(url: string): string {\n let protocol: string;\n try {\n protocol = new URL(url).protocol;\n } catch {\n throw new Error(\"only http and https URLs can be posted to, not this URL\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);\n return url;\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(postable(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. A start before the year 1 or after 9999 is null. */\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: isoTime(run.startedAt), 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","import type { AlertChannel } from \"../types.js\";\nimport { postable } from \"./shared.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\n/**\n * The payload's version, sent as its first field. It goes up only if a\n * major release changes the payload in a way that is not additive; see\n * https://cronwatch.dev/schemas/webhook/1.json.\n */\nexport const WEBHOOK_SCHEMA = 1;\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 after a\n * version: { schema: 1, type, job, title, message, run, details, triage, at,\n * definition }. A redirect is an error: point the url at where the receiver\n * 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({ schema: WEBHOOK_SCHEMA, ...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 signature(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(postable(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/**\n * The webhook's signature of a body: the HMAC-SHA256 of the body with the\n * secret, as lowercase hex. A request carries it as\n * `X-CronWatch-Signature: sha256=<signature>`, so a receiver checks one with\n * the raw body it got (before any JSON parsing) and a constant-time compare.\n * Web Crypto, so it runs on Workers and Deno too. Every port has it, named\n * the same.\n */\nexport async function signature(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","// @cronwatch/sdk/webhook: the channel, and signature(), the one helper for\n// a receiver, named the same in every port.\nimport * as internal from \"../alerts/webhook.js\";\n\nexport { signature, webhook } from \"../alerts/webhook.js\";\nexport type { WebhookOptions } from \"../alerts/webhook.js\";\n\n/** @deprecated Renamed `signature`, the name every port uses; this name is no longer exported from 1.0. */\nexport const hmacSha256Hex = internal.signature;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/webhook.ts","../src/entries/webhook.ts"],"names":["signature"],"mappings":";AAiCO,SAAS,SAAS,GAAA,EAAqB;AAC5C,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI;AACF,IAAA,QAAA,GAAW,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,QAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,MAAM,yDAAyD,CAAA;AAAA,EAC3E;AACA,EAAA,IAAI,QAAA,KAAa,WAAW,QAAA,KAAa,QAAA,QAAgB,IAAI,KAAA,CAAM,CAAA,+CAAA,EAAkD,QAAQ,CAAA,CAAE,CAAA;AAC/H,EAAA,OAAO,GAAA;AACT;AAiCA,eAAsB,MAAM,QAAA,EAAmC;AAC7D,EAAA,IAAI;AACF,IAAA,MAAM,QAAA,CAAS,MAAM,MAAA,EAAO;AAAA,EAC9B,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;;;ACjEA,IAAM,UAAA,GAAa,GAAA;AAOZ,IAAM,cAAA,GAAiB,CAAA;AAE9B,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;AAQO,SAAS,QAAQ,OAAA,EAAuC;AAC7D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CAAA;AAC9F,MAAA,MAAM,MAAM,QAAQ,CAAA;AAAA,IACtB;AAAA,GACF;AACF;AAUA,eAAsB,SAAA,CAAU,QAAgB,IAAA,EAA+B;AAC7E,EAAA,MAAM,OAAA,GAAU,IAAI,WAAA,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,MAAMA,UAAAA,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,CAAKA,UAAAA,EAAW,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC9E;;;ACpEO,IAAM,aAAA,GAAyB","file":"webhook.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 { isoTime } from \"../duration.js\";\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\" || type === \"under_floor\") 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/**\n * The URL, once it is one fetch can post to. Refused without quoting it:\n * fetch's own error for a URL it cannot parse (\"Failed to parse URL from ...\")\n * quotes the whole URL, and a webhook URL's path is its credential.\n */\nexport function postable(url: string): string {\n let protocol: string;\n try {\n protocol = new URL(url).protocol;\n } catch {\n throw new Error(\"only http and https URLs can be posted to, not this URL\");\n }\n if (protocol !== \"http:\" && protocol !== \"https:\") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);\n return url;\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(postable(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 await drain(response);\n return response;\n}\n\n/**\n * Lets go of a successful answer's body, which nothing reads, so its\n * connection goes back to the pool now rather than when it is collected.\n */\nexport async function drain(response: Response): Promise<void> {\n try {\n await response.body?.cancel();\n } catch {\n // Already read, or the connection is gone: nothing to let go of.\n }\n}\n\n/**\n * The parts of a webhook URL that are its credential, to cut from an error\n * body that echoes the request: its path and query together, then the last\n * segment of its path (Slack's and Discord's token) on its own.\n */\nexport function urlSecrets(url: string): string[] {\n try {\n const parsed = new URL(url);\n const last = parsed.pathname.split(\"/\").pop() ?? \"\";\n return [parsed.pathname + parsed.search, last].filter((part) => part.length > 0 && part !== \"/\");\n } catch {\n return [];\n }\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. A start before the year 1 or after 9999 is null. */\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: isoTime(run.startedAt), 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","import type { AlertChannel } from \"../types.js\";\nimport { drain, postable } from \"./shared.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. An empty string (an unset variable read as \"\", say) signs\n * nothing, and each send reports that to onError.\n */\n secret?: string;\n}\n\nconst TIMEOUT_MS = 10_000;\n\n/**\n * The payload's version, sent as its first field. It goes up only if a\n * major release changes the payload in a way that is not additive; see\n * https://cronwatch.dev/schemas/webhook/1.json.\n */\nexport const WEBHOOK_SCHEMA = 1;\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 after a\n * version: { schema: 1, type, job, title, message, run, details, triage, at,\n * definition }. A redirect is an error: point the url at where the receiver\n * 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, context) {\n const body = JSON.stringify({ schema: WEBHOOK_SCHEMA, ...alert });\n if (options.secret === \"\") {\n context?.onError?.(new Error(\"webhook: secret is an empty string, so this request is sent unsigned; set the secret, or leave it out to send unsigned on purpose\"));\n }\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 signature(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(postable(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 await drain(response);\n },\n };\n}\n\n/**\n * The webhook's signature of a body: the HMAC-SHA256 of the body with the\n * secret, as lowercase hex. A request carries it as\n * `X-CronWatch-Signature: sha256=<signature>`, so a receiver checks one with\n * the raw body it got (before any JSON parsing) and a constant-time compare.\n * Web Crypto, so it runs on Workers and Deno too. Every port has it, named\n * the same.\n */\nexport async function signature(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","// @cronwatch/sdk/webhook: the channel, and signature(), the one helper for\n// a receiver, named the same in every port.\nimport * as internal from \"../alerts/webhook.js\";\n\nexport { signature, webhook } from \"../alerts/webhook.js\";\nexport type { WebhookOptions } from \"../alerts/webhook.js\";\n\n/** @deprecated Renamed `signature`, the name every port uses; this name leaves the exports in 1.0. */\nexport const hmacSha256Hex = internal.signature;\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cronwatch/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Cron and scheduled-job monitoring that lives inside your app. Wrap a job, mount a route, get told when it is missed, failed, slow or over budget. No server to run.",
|
|
3
|
+
"version": "0.13.0",
|
|
4
|
+
"description": "Cron and scheduled-job monitoring that lives inside your app. Wrap a job, mount a route, get told when it is missed, failed, slow, or over budget. No server to run.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|