@cronwatch/sdk 0.12.3 → 0.12.5
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/LICENSE +1 -1
- 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.map +1 -1
- package/dist/bugsnag.d.cts +1 -1
- package/dist/bugsnag.d.ts +1 -1
- package/dist/bugsnag.js.map +1 -1
- package/dist/{client-DySsV5T0.d.ts → client-CFJUFEOg.d.cts} +14 -14
- package/dist/{client-BkPMRkDq.d.cts → client-k5UVIH38.d.ts} +14 -14
- 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.map +1 -1
- package/dist/datadog.d.cts +2 -2
- package/dist/datadog.d.ts +2 -2
- package/dist/datadog.js.map +1 -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.map +1 -1
- package/dist/{email-Bx3ehK0O.d.ts → email-CPoxD8--.d.ts} +3 -3
- package/dist/{email-CD6NO8CV.d.cts → email-U0hYRnPa.d.cts} +3 -3
- 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.map +1 -1
- package/dist/index.cjs +17 -13
- 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 +17 -13
- package/dist/index.js.map +1 -1
- 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.map +1 -1
- 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.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 +1 -1
- 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 +1 -1
- package/dist/postgres.js.map +1 -1
- 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.map +1 -1
- 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.map +1 -1
- 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.map +1 -1
- 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.map +1 -1
- 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.map +1 -1
- 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.map +1 -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.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.map +1 -1
- package/dist/twilio.d.cts +5 -5
- package/dist/twilio.d.ts +5 -5
- package/dist/twilio.js.map +1 -1
- package/dist/{types-Bm972Uqj.d.cts → types-V8SN54o9.d.cts} +7 -7
- package/dist/{types-Bm972Uqj.d.ts → types-V8SN54o9.d.ts} +7 -7
- package/dist/webhook.cjs.map +1 -1
- package/dist/webhook.d.cts +2 -2
- package/dist/webhook.d.ts +2 -2
- package/dist/webhook.js.map +1 -1
- package/package.json +3 -3
package/dist/twilio.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/twilio.ts","../src/entries/twilio.ts"],"names":["MAX_SEGMENTS","MAX_BODY","smsSegments","smsBody"],"mappings":";AAQO,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;AAOO,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;AAGO,IAAM,cAAA,GAAiB,GAAA;AAW9B,eAAsB,KAAK,QAAA,EAAkB,GAAA,EAAa,IAAA,EAAyD,OAAA,GAAkC,EA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A,EAAA,OAAO,GAAA,CAAI,IAAA,GAAO,IAAA,EAAM,QAAQ,CAAA;AAClC;AAGA,SAAS,cAAc,QAAA,EAAsC;AAC3D,EAAA,MAAM,CAAA,GAAI,OAAO,QAAA,KAAa,QAAA,IAAY,MAAA,CAAO,QAAA,CAAS,QAAQ,CAAA,GAAI,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA,GAAI,CAAA;AAC7F,EAAA,OAAO,KAAK,GAAA,CAAI,YAAA,EAAc,KAAK,GAAA,CAAI,CAAA,EAAG,CAAC,CAAC,CAAA;AAC9C;;;AC5JO,IAAMA,aAAAA,GAAwB;AAE9B,IAAMC,SAAAA,GAAoB;AAE1B,IAAMC,YAAAA,GAAuB;AAE7B,IAAMC,QAAAA,GAAmB","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 { 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","/**\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","// @cronwatch/sdk/twilio: what the entry point exports. The helpers the\n// channel is built from are internal; the names below are kept, deprecated,\n// for anyone who imported them, and are no longer exported from 1.0.\nimport * as internal from \"../alerts/twilio.js\";\n\nexport { twilio } from \"../alerts/twilio.js\";\nexport type { TwilioOptions } from \"../alerts/twilio.js\";\n\n/** @deprecated Internal to the Twilio channel; no longer exported from 1.0. */\nexport const MAX_SEGMENTS = internal.MAX_SEGMENTS;\n/** @deprecated Internal to the Twilio channel; no longer exported from 1.0. */\nexport const MAX_BODY = internal.MAX_BODY;\n/** @deprecated Internal to the Twilio channel; no longer exported from 1.0. */\nexport const smsSegments = internal.smsSegments;\n/** @deprecated Internal to the Twilio channel; no longer exported from 1.0. */\nexport const smsBody = internal.smsBody;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/twilio.ts","../src/entries/twilio.ts"],"names":["MAX_SEGMENTS","MAX_BODY","smsSegments","smsBody"],"mappings":";AAQO,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;AAOO,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;AAGO,IAAM,cAAA,GAAiB,GAAA;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AAA,CAAE,IAAA,CAAK,EAAE,CAAA,GAAI,KAAA;AAC7E,IAAA;AAAA,EACF;AAEA,EAAA,OAAO,GAAA,CAAI,IAAA,GAAO,IAAA,EAAM,QAAQ,CAAA;AAClC;AAGA,SAAS,cAAc,QAAA,EAAsC;AAC3D,EAAA,MAAM,CAAA,GAAI,OAAO,QAAA,KAAa,QAAA,IAAY,MAAA,CAAO,QAAA,CAAS,QAAQ,CAAA,GAAI,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA,GAAI,CAAA;AAC7F,EAAA,OAAO,KAAK,GAAA,CAAI,YAAA,EAAc,KAAK,GAAA,CAAI,CAAA,EAAG,CAAC,CAAC,CAAA;AAC9C;;;AC5JO,IAAMA,aAAAA,GAAwB;AAE9B,IAAMC,SAAAA,GAAoB;AAE1B,IAAMC,YAAAA,GAAuB;AAE7B,IAAMC,QAAAA,GAAmB","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 { 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","/**\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","// @cronwatch/sdk/twilio: what the entry point exports. The helpers the\n// channel is built from are internal; the names below are kept, deprecated,\n// for anyone who imported them, and leave the exports in 1.0.\nimport * as internal from \"../alerts/twilio.js\";\n\nexport { twilio } from \"../alerts/twilio.js\";\nexport type { TwilioOptions } from \"../alerts/twilio.js\";\n\n/** @deprecated Internal to the Twilio channel; leaves the exports in 1.0. */\nexport const MAX_SEGMENTS = internal.MAX_SEGMENTS;\n/** @deprecated Internal to the Twilio channel; leaves the exports in 1.0. */\nexport const MAX_BODY = internal.MAX_BODY;\n/** @deprecated Internal to the Twilio channel; leaves the exports in 1.0. */\nexport const smsSegments = internal.smsSegments;\n/** @deprecated Internal to the Twilio channel; leaves the exports in 1.0. */\nexport const smsBody = internal.smsBody;\n"]}
|
|
@@ -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
|
}
|
|
@@ -193,7 +193,7 @@ interface AlertBase {
|
|
|
193
193
|
message: string;
|
|
194
194
|
/**
|
|
195
195
|
* 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
|
|
196
|
+
* when triage was tried and gave nothing (it threw, timed out, or answered
|
|
197
197
|
* empty); it is not tried again for this alert.
|
|
198
198
|
*/
|
|
199
199
|
triage?: string | null;
|
|
@@ -225,9 +225,9 @@ interface AlertChannel {
|
|
|
225
225
|
send(alert: Alert, context?: ChannelContext): Promise<void>;
|
|
226
226
|
}
|
|
227
227
|
/**
|
|
228
|
-
* Where jobs, runs and state are kept. A store holds text without U+0000,
|
|
228
|
+
* Where jobs, runs, and state are kept. A store holds text without U+0000,
|
|
229
229
|
* 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
|
|
230
|
+
* error, and metric names, and from every key and string of a definition and
|
|
231
231
|
* a state, as it writes them. Job names and run ids never hold one.
|
|
232
232
|
*/
|
|
233
233
|
interface Store {
|
|
@@ -240,7 +240,7 @@ interface Store {
|
|
|
240
240
|
insertRun(run: Run): Promise<void>;
|
|
241
241
|
updateRun(run: Run): Promise<void>;
|
|
242
242
|
/**
|
|
243
|
-
* Write a run's status, finishedAt, durationMs, error, output and metrics
|
|
243
|
+
* Write a run's status, finishedAt, durationMs, error, output, and metrics
|
|
244
244
|
* only when its stored status is one of `fromStatuses`, in one step (SQL:
|
|
245
245
|
* `UPDATE ... WHERE id = ? AND status IN (...)`). Returns whether it wrote.
|
|
246
246
|
* This is what lets exactly one of several processes finishing the same run
|
|
@@ -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
|
}
|
|
@@ -193,7 +193,7 @@ interface AlertBase {
|
|
|
193
193
|
message: string;
|
|
194
194
|
/**
|
|
195
195
|
* 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
|
|
196
|
+
* when triage was tried and gave nothing (it threw, timed out, or answered
|
|
197
197
|
* empty); it is not tried again for this alert.
|
|
198
198
|
*/
|
|
199
199
|
triage?: string | null;
|
|
@@ -225,9 +225,9 @@ interface AlertChannel {
|
|
|
225
225
|
send(alert: Alert, context?: ChannelContext): Promise<void>;
|
|
226
226
|
}
|
|
227
227
|
/**
|
|
228
|
-
* Where jobs, runs and state are kept. A store holds text without U+0000,
|
|
228
|
+
* Where jobs, runs, and state are kept. A store holds text without U+0000,
|
|
229
229
|
* 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
|
|
230
|
+
* error, and metric names, and from every key and string of a definition and
|
|
231
231
|
* a state, as it writes them. Job names and run ids never hold one.
|
|
232
232
|
*/
|
|
233
233
|
interface Store {
|
|
@@ -240,7 +240,7 @@ interface Store {
|
|
|
240
240
|
insertRun(run: Run): Promise<void>;
|
|
241
241
|
updateRun(run: Run): Promise<void>;
|
|
242
242
|
/**
|
|
243
|
-
* Write a run's status, finishedAt, durationMs, error, output and metrics
|
|
243
|
+
* Write a run's status, finishedAt, durationMs, error, output, and metrics
|
|
244
244
|
* only when its stored status is one of `fromStatuses`, in one step (SQL:
|
|
245
245
|
* `UPDATE ... WHERE id = ? AND status IN (...)`). Returns whether it wrote.
|
|
246
246
|
* This is what lets exactly one of several processes finishing the same run
|
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,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,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AAA,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;;;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,IAAI,MAAM,uBAAuB,CAAA;AACzD,EAAA,OAAO;AAA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AAQ,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 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-V8SN54o9.cjs';
|
|
2
2
|
|
|
3
3
|
interface WebhookOptions {
|
|
4
4
|
url: string;
|
|
@@ -28,7 +28,7 @@ declare function webhook(options: WebhookOptions): AlertChannel;
|
|
|
28
28
|
*/
|
|
29
29
|
declare function signature(secret: string, body: string): Promise<string>;
|
|
30
30
|
|
|
31
|
-
/** @deprecated Renamed `signature`, the name every port uses; this name
|
|
31
|
+
/** @deprecated Renamed `signature`, the name every port uses; this name leaves the exports in 1.0. */
|
|
32
32
|
declare const hmacSha256Hex: typeof signature;
|
|
33
33
|
|
|
34
34
|
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-V8SN54o9.js';
|
|
2
2
|
|
|
3
3
|
interface WebhookOptions {
|
|
4
4
|
url: string;
|
|
@@ -28,7 +28,7 @@ declare function webhook(options: WebhookOptions): AlertChannel;
|
|
|
28
28
|
*/
|
|
29
29
|
declare function signature(secret: string, body: string): Promise<string>;
|
|
30
30
|
|
|
31
|
-
/** @deprecated Renamed `signature`, the name every port uses; this name
|
|
31
|
+
/** @deprecated Renamed `signature`, the name every port uses; this name leaves the exports in 1.0. */
|
|
32
32
|
declare const hmacSha256Hex: typeof signature;
|
|
33
33
|
|
|
34
34
|
export { type WebhookOptions, hmacSha256Hex, signature, webhook };
|
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,IAAI,MAAM,uBAAuB,CAAA;AACzD,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,SAAA;AAAA,IACN,MAAM,KAAK,KAAA,EAAO;AAChB,MAAA,MAAM,IAAA,GAAO,KAAK,SAAA,CAAU,EAAE,QAAQ,cAAA,EAAgB,GAAG,OAAO,CAAA;AAChE,MAAA,MAAM,OAAA,GAAkC,EAAE,cAAA,EAAgB,kBAAA,EAAoB,cAAc,WAAA,EAAY;AAExG,MAAA,KAAA,MAAW,CAAC,IAAA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,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;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AG,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 leaves the exports in 1.0. */\nexport const hmacSha256Hex = internal.signature;\n"]}
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cronwatch/sdk",
|
|
3
|
-
"version": "0.12.
|
|
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.12.5",
|
|
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",
|
|
8
|
-
"url": "git+https://github.com/
|
|
8
|
+
"url": "git+https://github.com/cronwatchdev/cronwatch.git",
|
|
9
9
|
"directory": "packages/sdk"
|
|
10
10
|
},
|
|
11
11
|
"homepage": "https://cronwatch.dev",
|