@cronwatch/sdk 0.4.0 → 0.5.1

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.
Files changed (65) hide show
  1. package/dist/bugsnag.cjs +11 -1
  2. package/dist/bugsnag.cjs.map +1 -1
  3. package/dist/bugsnag.js +11 -1
  4. package/dist/bugsnag.js.map +1 -1
  5. package/dist/datadog.cjs +11 -1
  6. package/dist/datadog.cjs.map +1 -1
  7. package/dist/datadog.js +11 -1
  8. package/dist/datadog.js.map +1 -1
  9. package/dist/discord.cjs +13 -1
  10. package/dist/discord.cjs.map +1 -1
  11. package/dist/discord.js +13 -1
  12. package/dist/discord.js.map +1 -1
  13. package/dist/honeybadger.cjs +11 -1
  14. package/dist/honeybadger.cjs.map +1 -1
  15. package/dist/honeybadger.js +11 -1
  16. package/dist/honeybadger.js.map +1 -1
  17. package/dist/index.cjs +776 -134
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.js +776 -134
  20. package/dist/index.js.map +1 -1
  21. package/dist/mailgun.cjs +11 -1
  22. package/dist/mailgun.cjs.map +1 -1
  23. package/dist/mailgun.js +11 -1
  24. package/dist/mailgun.js.map +1 -1
  25. package/dist/newrelic.cjs +11 -1
  26. package/dist/newrelic.cjs.map +1 -1
  27. package/dist/newrelic.js +11 -1
  28. package/dist/newrelic.js.map +1 -1
  29. package/dist/postmark.cjs +11 -1
  30. package/dist/postmark.cjs.map +1 -1
  31. package/dist/postmark.js +11 -1
  32. package/dist/postmark.js.map +1 -1
  33. package/dist/resend.cjs +11 -1
  34. package/dist/resend.cjs.map +1 -1
  35. package/dist/resend.js +11 -1
  36. package/dist/resend.js.map +1 -1
  37. package/dist/rollbar.cjs +11 -1
  38. package/dist/rollbar.cjs.map +1 -1
  39. package/dist/rollbar.js +11 -1
  40. package/dist/rollbar.js.map +1 -1
  41. package/dist/sendgrid.cjs +11 -1
  42. package/dist/sendgrid.cjs.map +1 -1
  43. package/dist/sendgrid.js +11 -1
  44. package/dist/sendgrid.js.map +1 -1
  45. package/dist/sentry.cjs +11 -1
  46. package/dist/sentry.cjs.map +1 -1
  47. package/dist/sentry.js +11 -1
  48. package/dist/sentry.js.map +1 -1
  49. package/dist/ses.cjs +11 -1
  50. package/dist/ses.cjs.map +1 -1
  51. package/dist/ses.js +11 -1
  52. package/dist/ses.js.map +1 -1
  53. package/dist/slack.cjs +13 -1
  54. package/dist/slack.cjs.map +1 -1
  55. package/dist/slack.js +13 -1
  56. package/dist/slack.js.map +1 -1
  57. package/dist/twilio.cjs +11 -1
  58. package/dist/twilio.cjs.map +1 -1
  59. package/dist/twilio.js +11 -1
  60. package/dist/twilio.js.map +1 -1
  61. package/dist/webhook.cjs +13 -1
  62. package/dist/webhook.cjs.map +1 -1
  63. package/dist/webhook.js +13 -1
  64. package/dist/webhook.js.map +1 -1
  65. package/package.json +1 -1
package/dist/bugsnag.cjs CHANGED
@@ -14,9 +14,19 @@ function origin(url) {
14
14
  return "(invalid URL)";
15
15
  }
16
16
  }
17
+ function postable(url) {
18
+ let protocol;
19
+ try {
20
+ protocol = new URL(url).protocol;
21
+ } catch {
22
+ throw new Error("only http and https URLs can be posted to, not this URL");
23
+ }
24
+ if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
25
+ return url;
26
+ }
17
27
  var ERROR_BODY_MAX = 200;
18
28
  async function post(provider, url, init, secrets = []) {
19
- const response = await fetch(url, { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
29
+ const response = await fetch(postable(url), { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
20
30
  if (!response.ok) {
21
31
  let text = "";
22
32
  try {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/bugsnag.ts"],"names":[],"mappings":";;;AAOO,IAAM,UAAA,GAAa,GAAA;AAKnB,SAAS,SAAS,IAAA,EA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AgB,EAAE,IAAA,EAAM,kBAAA,EAAmB;AAAA,YAC3C,SAAS,KAAA,CAAM,GAAA;AAAA,YACf,cAAc,CAAA,UAAA,EAAa,KAAA,CAAM,GAAG,CAAA,CAAA,EAAI,MAAM,IAAI,CAAA,CAAA;AAAA,YAClD,QAAA,EAAU;AAAA,cACR,SAAA,EAAW;AAAA,gBACT,KAAK,KAAA,CAAM,GAAA;AAAA,gBACX,MAAM,KAAA,CAAM,IAAA;AAAA,gBACZ,GAAI,MAAM,MAAA,GAAS,EAAE,QAAQ,KAAA,CAAM,MAAA,KAAW,EAAC;AAAA,gBAC/C,GAAI,IAAA,GAAO,EAAE,IAAA,KAAS,EAAC;AAAA,gBACvB,SAAS,KAAA,CAAM,OAAA;AAAA,gBACf,GAAA,EAAK,WAAW,KAAK;AAAA;AACvB,aACF;AAAA,YACA,GAAA,EAAK,EAAE,YAAA,EAAc,OAAA,CAAQ,gBAAgB,YAAA,EAAa;AAAA,YAC1D,MAAA,EAAQ,EAAE,IAAA,EAAM,IAAI,KAAK,KAAA,CAAM,EAAE,CAAA,CAAE,WAAA,EAAY;AAAE;AACnD;AACF,OACF;AACA,MAAA,MAAM,IAAA,CAAK,WAAW,GAAA,EAAK;AAAA,QACzB,OAAA,EAAS;AAAA,UACP,cAAA,EAAgB,kBAAA;AAAA,UAChB,iBAAA,EAAmB,MAAA;AAAA,UACnB,yBAAA,EAA2B,GAAA;AAAA,UAC3B,mBAAmB,IAAI,IAAA,CAAK,GAAA,EAAK,EAAE,WAAA;AAAY,SACjD;AAAA,QACA,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,OAAO;AAAA,OAC9B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF","file":"bugsnag.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 type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/** How much of a provider's error body goes into the error message. */\nexport const ERROR_BODY_MAX = 200;\n\n/**\n * POSTs and throws on a non-2xx answer. The error names the provider and the\n * URL's origin, plus the start of the response body with every secret the\n * channel holds cut out, in case a provider echoes one back. Secrets are cut\n * from a prefix long enough to hold one that starts inside the first\n * ERROR_BODY_MAX characters, and only then is it cut to that length, so no\n * part of a secret survives at the edge. A redirect is refused rather than\n * followed: the credential headers would go with it to wherever it points.\n */\nexport async function post(provider: string, url: string, init: { headers: Record<string, string>; body: string }, secrets: (string | undefined)[] = []): Promise<Response> {\n const response = await fetch(url, { method: \"POST\", headers: init.headers, body: init.body, redirect: \"error\", signal: AbortSignal.timeout(TIMEOUT_MS) });\n if (!response.ok) {\n let text = \"\";\n try {\n text = await response.text();\n } catch {\n // The status is enough.\n }\n throw new Error(`${provider} ${origin(url)} answered ${response.status}${text ? `: ${errorBody(text, secrets)}` : \"\"}`);\n }\n return response;\n}\n\n/** The start of an error body, secrets cut out first, then cut to ERROR_BODY_MAX on a code point. */\nexport function errorBody(text: string, secrets: (string | undefined)[] = []): string {\n const kept = secrets.filter((s): s is string => typeof s === \"string\" && s.length >= 4);\n const longest = kept.reduce((n, s) => Math.max(n, s.length), 0);\n let head = cut(text, ERROR_BODY_MAX + longest);\n for (const secret of kept) head = head.split(secret).join(\"[redacted]\");\n return cut(head, ERROR_BODY_MAX);\n}\n\n/** A credential with the spaces and newlines a paste leaves around it taken off. Anything not a string is empty. */\nexport function trimmed(value: unknown): string {\n return typeof value === \"string\" ? value.trim() : \"\";\n}\n\n/** Base64 of UTF-8, without Buffer. */\nexport function base64(text: string): string {\n let binary = \"\";\n for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nexport function basicAuth(user: string, password: string): string {\n return `Basic ${base64(`${user}:${password}`)}`;\n}\n\nexport function hex(bytes: ArrayBuffer | Uint8Array): string {\n return Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function sha256Hex(text: string): Promise<string> {\n return hex(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text)));\n}\n\n/**\n * A stable 32 hex character id for one alert: the same job, type and time\n * always give the same id, so a provider that deduplicates on it drops a\n * resend of an alert it already took.\n */\nexport async function alertId(alert: Alert): Promise<string> {\n return (await sha256Hex(`${alert.job}\\n${alert.type}\\n${alert.at}`)).slice(0, 32);\n}\n\n/** The same id laid out as a UUID, for APIs that ask for one. */\nexport function asUuid(id: string): string {\n return `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20, 32)}`;\n}\n\n/** Cuts to at most `max` UTF-16 units without splitting a surrogate pair. */\nexport function cut(text: string, max: number): string {\n if (text.length <= max) return text;\n let end = max;\n const code = text.charCodeAt(end - 1);\n if (code >= 0xd800 && code <= 0xdbff) end -= 1;\n return text.slice(0, end);\n}\n\n/** The run fields worth attaching to a tracker event. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Bugsnag, Error Reporting API, payload version 5.\n * API reference: https://developer.smartbear.com/bugsnag/docs/reporting-events-and-sessions\n * (formerly https://bugsnagerrorreportingapi.docs.apiary.io/)\n * POST https://notify.bugsnag.com/ with Bugsnag-Api-Key.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, post, runSummary, severity, trimmed } from \"./shared.js\";\n\nexport interface BugsnagOptions {\n /** The project's notifier API key. */\n apiKey: string;\n /** Defaults to \"production\". */\n releaseStage?: string;\n /** Another notify endpoint, for on-premise installs. Defaults to https://notify.bugsnag.com/. */\n endpoint?: string;\n /** Also send recoveries, as info events. Defaults to false, since each one is an event on an error. */\n recovered?: boolean;\n /** The clock for the Bugsnag-Sent-At header, in epoch milliseconds. For tests. */\n now?: () => number;\n link?: (alert: Alert) => string;\n}\n\n/** Reports alerts to Bugsnag, grouped per job and alert type. */\nexport function bugsnag(options: BugsnagOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"bugsnag() needs an apiKey\");\n const url = options.endpoint ?? \"https://notify.bugsnag.com/\";\n const now = options.now ?? Date.now;\n return {\n name: \"bugsnag\",\n async send(alert) {\n if (alert.type === \"recovered\" && !options.recovered) return;\n const link = options.link?.(alert);\n const payload = {\n apiKey,\n payloadVersion: \"5\",\n // The notifier's own version, not the SDK's; Bugsnag asks for one.\n notifier: { name: \"cronwatch\", version: \"1.0.0\", url: \"https://cronwatch.dev\" },\n events: [\n {\n exceptions: [{ errorClass: `CronWatch ${alert.type}`, message: cut(`${alert.title}\\n${alert.message}`, 8000), stacktrace: [], type: \"nodejs\" }],\n severity: severity(alert.type),\n unhandled: false,\n severityReason: { type: \"handledException\" },\n context: alert.job,\n groupingHash: `cronwatch:${alert.job}:${alert.type}`,\n metaData: {\n cronwatch: {\n job: alert.job,\n type: alert.type,\n ...(alert.triage ? { triage: alert.triage } : {}),\n ...(link ? { link } : {}),\n details: alert.details,\n run: runSummary(alert),\n },\n },\n app: { releaseStage: options.releaseStage ?? \"production\" },\n device: { time: new Date(alert.at).toISOString() },\n },\n ],\n };\n await post(\"Bugsnag\", url, {\n headers: {\n \"content-type\": \"application/json\",\n \"bugsnag-api-key\": apiKey,\n \"bugsnag-payload-version\": \"5\",\n \"bugsnag-sent-at\": new Date(now()).toISOString(),\n },\n body: JSON.stringify(payload),\n }, [apiKey]);\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/bugsnag.ts"],"names":[],"mappings":";;;AAOO,IAAM,UAAA,GAAa,GAAA;AAKnB,SAAS,SAAS,IAAA,EAA+B;AACtD,EAAA,IAAI,IAAA,KAAS,aAAa,OAAO,MAAA;AACjC,EAAA,IAAI,IAAA,KAAS,MAAA,IAAU,IAAA,KAAS,aAAA,EAAe,OAAO,SAAA;AACtD,EAAA,OAAO,OAAA;AACT;AAGO,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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E,IAAA,KAAS,EAAC;AAAA,gBACvB,SAAS,KAAA,CAAM,OAAA;AAAA,gBACf,GAAA,EAAK,WAAW,KAAK;AAAA;AACvB,aACF;AAAA,YACA,GAAA,EAAK,EAAE,YAAA,EAAc,OAAA,CAAQ,gBAAgB,YAAA,EAAa;AAAA,YAC1D,MAAA,EAAQ,EAAE,IAAA,EAAM,IAAI,KAAK,KAAA,CAAM,EAAE,CAAA,CAAE,WAAA,EAAY;AAAE;AACnD;AACF,OACF;AACA,MAAA,MAAM,IAAA,CAAK,WAAW,GAAA,EAAK;AAAA,QACzB,OAAA,EAAS;AAAA,UACP,cAAA,EAAgB,kBAAA;AAAA,UAChB,iBAAA,EAAmB,MAAA;AAAA,UACnB,yBAAA,EAA2B,GAAA;AAAA,UAC3B,mBAAmB,IAAI,IAAA,CAAK,GAAA,EAAK,EAAE,WAAA;AAAY,SACjD;AAAA,QACA,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,OAAO;AAAA,OAC9B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF","file":"bugsnag.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 type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/**\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. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Bugsnag, Error Reporting API, payload version 5.\n * API reference: https://developer.smartbear.com/bugsnag/docs/reporting-events-and-sessions\n * (formerly https://bugsnagerrorreportingapi.docs.apiary.io/)\n * POST https://notify.bugsnag.com/ with Bugsnag-Api-Key.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, post, runSummary, severity, trimmed } from \"./shared.js\";\n\nexport interface BugsnagOptions {\n /** The project's notifier API key. */\n apiKey: string;\n /** Defaults to \"production\". */\n releaseStage?: string;\n /** Another notify endpoint, for on-premise installs. Defaults to https://notify.bugsnag.com/. */\n endpoint?: string;\n /** Also send recoveries, as info events. Defaults to false, since each one is an event on an error. */\n recovered?: boolean;\n /** The clock for the Bugsnag-Sent-At header, in epoch milliseconds. For tests. */\n now?: () => number;\n link?: (alert: Alert) => string;\n}\n\n/** Reports alerts to Bugsnag, grouped per job and alert type. */\nexport function bugsnag(options: BugsnagOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"bugsnag() needs an apiKey\");\n const url = options.endpoint ?? \"https://notify.bugsnag.com/\";\n const now = options.now ?? Date.now;\n return {\n name: \"bugsnag\",\n async send(alert) {\n if (alert.type === \"recovered\" && !options.recovered) return;\n const link = options.link?.(alert);\n const payload = {\n apiKey,\n payloadVersion: \"5\",\n // The notifier's own version, not the SDK's; Bugsnag asks for one.\n notifier: { name: \"cronwatch\", version: \"1.0.0\", url: \"https://cronwatch.dev\" },\n events: [\n {\n exceptions: [{ errorClass: `CronWatch ${alert.type}`, message: cut(`${alert.title}\\n${alert.message}`, 8000), stacktrace: [], type: \"nodejs\" }],\n severity: severity(alert.type),\n unhandled: false,\n severityReason: { type: \"handledException\" },\n context: alert.job,\n groupingHash: `cronwatch:${alert.job}:${alert.type}`,\n metaData: {\n cronwatch: {\n job: alert.job,\n type: alert.type,\n ...(alert.triage ? { triage: alert.triage } : {}),\n ...(link ? { link } : {}),\n details: alert.details,\n run: runSummary(alert),\n },\n },\n app: { releaseStage: options.releaseStage ?? \"production\" },\n device: { time: new Date(alert.at).toISOString() },\n },\n ],\n };\n await post(\"Bugsnag\", url, {\n headers: {\n \"content-type\": \"application/json\",\n \"bugsnag-api-key\": apiKey,\n \"bugsnag-payload-version\": \"5\",\n \"bugsnag-sent-at\": new Date(now()).toISOString(),\n },\n body: JSON.stringify(payload),\n }, [apiKey]);\n },\n };\n}\n"]}
package/dist/bugsnag.js CHANGED
@@ -12,9 +12,19 @@ function origin(url) {
12
12
  return "(invalid URL)";
13
13
  }
14
14
  }
15
+ function postable(url) {
16
+ let protocol;
17
+ try {
18
+ protocol = new URL(url).protocol;
19
+ } catch {
20
+ throw new Error("only http and https URLs can be posted to, not this URL");
21
+ }
22
+ if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
23
+ return url;
24
+ }
15
25
  var ERROR_BODY_MAX = 200;
16
26
  async function post(provider, url, init, secrets = []) {
17
- const response = await fetch(url, { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
27
+ const response = await fetch(postable(url), { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
18
28
  if (!response.ok) {
19
29
  let text = "";
20
30
  try {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/bugsnag.ts"],"names":[],"mappings":";AAOO,IAAM,UAAA,GAAa,GAAA;AAKnB,SAAS,SAAS,IAAA,EAA+B;AACtD,EAAA,IAAI,IAAA,KAAS,aAAa,OAAO,MAAA;AACjC,EAAA,IAAI,IAAA,KAAS,MAAA,IAAU,IAAA,KAAS,aAAA,EAAe,OAAO,SAAA;AACtD,EAAA,OAAO,OAAA;AACT;AAGO,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,MAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,eAAA;AAAA,EACT;AACF;AAGO,IAAM,cAAA,GAAiB,GAAA;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AAA,gBAC/C,GAAI,IAAA,GAAO,EAAE,IAAA,KAAS,EAAC;AAAA,gBACvB,SAAS,KAAA,CAAM,OAAA;AAAA,gBACf,GAAA,EAAK,WAAW,KAAK;AAAA;AACvB,aACF;AAAA,YACA,GAAA,EAAK,EAAE,YAAA,EAAc,OAAA,CAAQ,gBAAgB,YAAA,EAAa;AAAA,YAC1D,MAAA,EAAQ,EAAE,IAAA,EAAM,IAAI,KAAK,KAAA,CAAM,EAAE,CAAA,CAAE,WAAA,EAAY;AAAE;AACnD;AACF,OACF;AACA,MAAA,MAAM,IAAA,CAAK,WAAW,GAAA,EAAK;AAAA,QACzB,OAAA,EAAS;AAAA,UACP,cAAA,EAAgB,kBAAA;AAAA,UAChB,iBAAA,EAAmB,MAAA;AAAA,UACnB,yBAAA,EAA2B,GAAA;AAAA,UAC3B,mBAAmB,IAAI,IAAA,CAAK,GAAA,EAAK,EAAE,WAAA;AAAY,SACjD;AAAA,QACA,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,OAAO;AAAA,OAC9B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF","file":"bugsnag.js","sourcesContent":["/**\n * Helpers shared by the provider channels. Only fetch and Web Crypto, so the\n * channels run on Node, Cloudflare Workers, Deno and Bun alike. Not an entry\n * point: each channel bundles its own copy.\n */\nimport type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/** How much of a provider's error body goes into the error message. */\nexport const ERROR_BODY_MAX = 200;\n\n/**\n * POSTs and throws on a non-2xx answer. The error names the provider and the\n * URL's origin, plus the start of the response body with every secret the\n * channel holds cut out, in case a provider echoes one back. Secrets are cut\n * from a prefix long enough to hold one that starts inside the first\n * ERROR_BODY_MAX characters, and only then is it cut to that length, so no\n * part of a secret survives at the edge. A redirect is refused rather than\n * followed: the credential headers would go with it to wherever it points.\n */\nexport async function post(provider: string, url: string, init: { headers: Record<string, string>; body: string }, secrets: (string | undefined)[] = []): Promise<Response> {\n const response = await fetch(url, { method: \"POST\", headers: init.headers, body: init.body, redirect: \"error\", signal: AbortSignal.timeout(TIMEOUT_MS) });\n if (!response.ok) {\n let text = \"\";\n try {\n text = await response.text();\n } catch {\n // The status is enough.\n }\n throw new Error(`${provider} ${origin(url)} answered ${response.status}${text ? `: ${errorBody(text, secrets)}` : \"\"}`);\n }\n return response;\n}\n\n/** The start of an error body, secrets cut out first, then cut to ERROR_BODY_MAX on a code point. */\nexport function errorBody(text: string, secrets: (string | undefined)[] = []): string {\n const kept = secrets.filter((s): s is string => typeof s === \"string\" && s.length >= 4);\n const longest = kept.reduce((n, s) => Math.max(n, s.length), 0);\n let head = cut(text, ERROR_BODY_MAX + longest);\n for (const secret of kept) head = head.split(secret).join(\"[redacted]\");\n return cut(head, ERROR_BODY_MAX);\n}\n\n/** A credential with the spaces and newlines a paste leaves around it taken off. Anything not a string is empty. */\nexport function trimmed(value: unknown): string {\n return typeof value === \"string\" ? value.trim() : \"\";\n}\n\n/** Base64 of UTF-8, without Buffer. */\nexport function base64(text: string): string {\n let binary = \"\";\n for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nexport function basicAuth(user: string, password: string): string {\n return `Basic ${base64(`${user}:${password}`)}`;\n}\n\nexport function hex(bytes: ArrayBuffer | Uint8Array): string {\n return Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function sha256Hex(text: string): Promise<string> {\n return hex(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text)));\n}\n\n/**\n * A stable 32 hex character id for one alert: the same job, type and time\n * always give the same id, so a provider that deduplicates on it drops a\n * resend of an alert it already took.\n */\nexport async function alertId(alert: Alert): Promise<string> {\n return (await sha256Hex(`${alert.job}\\n${alert.type}\\n${alert.at}`)).slice(0, 32);\n}\n\n/** The same id laid out as a UUID, for APIs that ask for one. */\nexport function asUuid(id: string): string {\n return `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20, 32)}`;\n}\n\n/** Cuts to at most `max` UTF-16 units without splitting a surrogate pair. */\nexport function cut(text: string, max: number): string {\n if (text.length <= max) return text;\n let end = max;\n const code = text.charCodeAt(end - 1);\n if (code >= 0xd800 && code <= 0xdbff) end -= 1;\n return text.slice(0, end);\n}\n\n/** The run fields worth attaching to a tracker event. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Bugsnag, Error Reporting API, payload version 5.\n * API reference: https://developer.smartbear.com/bugsnag/docs/reporting-events-and-sessions\n * (formerly https://bugsnagerrorreportingapi.docs.apiary.io/)\n * POST https://notify.bugsnag.com/ with Bugsnag-Api-Key.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, post, runSummary, severity, trimmed } from \"./shared.js\";\n\nexport interface BugsnagOptions {\n /** The project's notifier API key. */\n apiKey: string;\n /** Defaults to \"production\". */\n releaseStage?: string;\n /** Another notify endpoint, for on-premise installs. Defaults to https://notify.bugsnag.com/. */\n endpoint?: string;\n /** Also send recoveries, as info events. Defaults to false, since each one is an event on an error. */\n recovered?: boolean;\n /** The clock for the Bugsnag-Sent-At header, in epoch milliseconds. For tests. */\n now?: () => number;\n link?: (alert: Alert) => string;\n}\n\n/** Reports alerts to Bugsnag, grouped per job and alert type. */\nexport function bugsnag(options: BugsnagOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"bugsnag() needs an apiKey\");\n const url = options.endpoint ?? \"https://notify.bugsnag.com/\";\n const now = options.now ?? Date.now;\n return {\n name: \"bugsnag\",\n async send(alert) {\n if (alert.type === \"recovered\" && !options.recovered) return;\n const link = options.link?.(alert);\n const payload = {\n apiKey,\n payloadVersion: \"5\",\n // The notifier's own version, not the SDK's; Bugsnag asks for one.\n notifier: { name: \"cronwatch\", version: \"1.0.0\", url: \"https://cronwatch.dev\" },\n events: [\n {\n exceptions: [{ errorClass: `CronWatch ${alert.type}`, message: cut(`${alert.title}\\n${alert.message}`, 8000), stacktrace: [], type: \"nodejs\" }],\n severity: severity(alert.type),\n unhandled: false,\n severityReason: { type: \"handledException\" },\n context: alert.job,\n groupingHash: `cronwatch:${alert.job}:${alert.type}`,\n metaData: {\n cronwatch: {\n job: alert.job,\n type: alert.type,\n ...(alert.triage ? { triage: alert.triage } : {}),\n ...(link ? { link } : {}),\n details: alert.details,\n run: runSummary(alert),\n },\n },\n app: { releaseStage: options.releaseStage ?? \"production\" },\n device: { time: new Date(alert.at).toISOString() },\n },\n ],\n };\n await post(\"Bugsnag\", url, {\n headers: {\n \"content-type\": \"application/json\",\n \"bugsnag-api-key\": apiKey,\n \"bugsnag-payload-version\": \"5\",\n \"bugsnag-sent-at\": new Date(now()).toISOString(),\n },\n body: JSON.stringify(payload),\n }, [apiKey]);\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/bugsnag.ts"],"names":[],"mappings":";AAOO,IAAM,UAAA,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;AAAA,UACP,cAAA,EAAgB,kBAAA;AAAA,UAChB,iBAAA,EAAmB,MAAA;AAAA,UACnB,yBAAA,EAA2B,GAAA;AAAA,UAC3B,mBAAmB,IAAI,IAAA,CAAK,GAAA,EAAK,EAAE,WAAA;AAAY,SACjD;AAAA,QACA,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,OAAO;AAAA,OAC9B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF","file":"bugsnag.js","sourcesContent":["/**\n * Helpers shared by the provider channels. Only fetch and Web Crypto, so the\n * channels run on Node, Cloudflare Workers, Deno and Bun alike. Not an entry\n * point: each channel bundles its own copy.\n */\nimport type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/**\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. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Bugsnag, Error Reporting API, payload version 5.\n * API reference: https://developer.smartbear.com/bugsnag/docs/reporting-events-and-sessions\n * (formerly https://bugsnagerrorreportingapi.docs.apiary.io/)\n * POST https://notify.bugsnag.com/ with Bugsnag-Api-Key.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, post, runSummary, severity, trimmed } from \"./shared.js\";\n\nexport interface BugsnagOptions {\n /** The project's notifier API key. */\n apiKey: string;\n /** Defaults to \"production\". */\n releaseStage?: string;\n /** Another notify endpoint, for on-premise installs. Defaults to https://notify.bugsnag.com/. */\n endpoint?: string;\n /** Also send recoveries, as info events. Defaults to false, since each one is an event on an error. */\n recovered?: boolean;\n /** The clock for the Bugsnag-Sent-At header, in epoch milliseconds. For tests. */\n now?: () => number;\n link?: (alert: Alert) => string;\n}\n\n/** Reports alerts to Bugsnag, grouped per job and alert type. */\nexport function bugsnag(options: BugsnagOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"bugsnag() needs an apiKey\");\n const url = options.endpoint ?? \"https://notify.bugsnag.com/\";\n const now = options.now ?? Date.now;\n return {\n name: \"bugsnag\",\n async send(alert) {\n if (alert.type === \"recovered\" && !options.recovered) return;\n const link = options.link?.(alert);\n const payload = {\n apiKey,\n payloadVersion: \"5\",\n // The notifier's own version, not the SDK's; Bugsnag asks for one.\n notifier: { name: \"cronwatch\", version: \"1.0.0\", url: \"https://cronwatch.dev\" },\n events: [\n {\n exceptions: [{ errorClass: `CronWatch ${alert.type}`, message: cut(`${alert.title}\\n${alert.message}`, 8000), stacktrace: [], type: \"nodejs\" }],\n severity: severity(alert.type),\n unhandled: false,\n severityReason: { type: \"handledException\" },\n context: alert.job,\n groupingHash: `cronwatch:${alert.job}:${alert.type}`,\n metaData: {\n cronwatch: {\n job: alert.job,\n type: alert.type,\n ...(alert.triage ? { triage: alert.triage } : {}),\n ...(link ? { link } : {}),\n details: alert.details,\n run: runSummary(alert),\n },\n },\n app: { releaseStage: options.releaseStage ?? \"production\" },\n device: { time: new Date(alert.at).toISOString() },\n },\n ],\n };\n await post(\"Bugsnag\", url, {\n headers: {\n \"content-type\": \"application/json\",\n \"bugsnag-api-key\": apiKey,\n \"bugsnag-payload-version\": \"5\",\n \"bugsnag-sent-at\": new Date(now()).toISOString(),\n },\n body: JSON.stringify(payload),\n }, [apiKey]);\n },\n };\n}\n"]}
package/dist/datadog.cjs CHANGED
@@ -9,9 +9,19 @@ function origin(url) {
9
9
  return "(invalid URL)";
10
10
  }
11
11
  }
12
+ function postable(url) {
13
+ let protocol;
14
+ try {
15
+ protocol = new URL(url).protocol;
16
+ } catch {
17
+ throw new Error("only http and https URLs can be posted to, not this URL");
18
+ }
19
+ if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
20
+ return url;
21
+ }
12
22
  var ERROR_BODY_MAX = 200;
13
23
  async function post(provider, url, init, secrets = []) {
14
- const response = await fetch(url, { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
24
+ const response = await fetch(postable(url), { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
15
25
  if (!response.ok) {
16
26
  let text = "";
17
27
  try {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/datadog.ts"],"names":[],"mappings":";;;AAOO,IAAM,UAAA,GAAa,GAAA;AAYnB,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,MAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,eAAA;AAAA,EACT;AACF;AAGO,IAAM,cAAA,GAAiB,GAAA;AAW9B,eAAsB,KAAK,QAAA,EAAkB,GAAA,EAAa,IAAA,EAAyD,OAAA,GAAkC,EAAC,EAAsB;AAC1K,EAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,GAAA,EAAK,EAAE,MAAA,EAAQ,MAAA,EAAQ,SAAS,IAAA,CAAK,OAAA,EAAS,MAAM,IAAA,CAAK,IAAA,EAAM,UAAU,OAAA,EAAS,MAAA,EAAQ,YAAY,OAAA,CAAQ,UAAU,GAAG,CAAA;AACxJ,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,IAAI,IAAA,GAAO,EAAA;AACX,IAAA,IAAI;AACF,MAAA,IAAA,GAAO,MAAM,SAAS,IAAA,EAAK;AAAA,IAC7B,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,IAAI,MAAM,CAAA,EAAG,QAAQ,IAAI,MAAA,CAAO,GAA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M,IAAA,CAAK,WAAW,GAAA,EAAK;AAAA,QACzB,SAAS,EAAE,cAAA,EAAgB,oBAAoB,MAAA,EAAQ,kBAAA,EAAoB,cAAc,MAAA,EAAO;AAAA,QAChG,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,KAAK;AAAA,OAC5B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF;AAGA,eAAe,eAAe,KAAA,EAA+B;AAC3D,EAAA,MAAM,MAAM,CAAA,UAAA,EAAa,KAAA,CAAM,GAAG,CAAA,CAAA,EAAI,MAAM,IAAI,CAAA,CAAA;AAChD,EAAA,OAAO,GAAA,CAAI,MAAA,IAAU,GAAA,GAAM,GAAA,GAAM,CAAA,UAAA,EAAA,CAAc,MAAM,SAAA,CAAU,GAAG,CAAA,EAAG,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA;AACnF","file":"datadog.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 type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/** How much of a provider's error body goes into the error message. */\nexport const ERROR_BODY_MAX = 200;\n\n/**\n * POSTs and throws on a non-2xx answer. The error names the provider and the\n * URL's origin, plus the start of the response body with every secret the\n * channel holds cut out, in case a provider echoes one back. Secrets are cut\n * from a prefix long enough to hold one that starts inside the first\n * ERROR_BODY_MAX characters, and only then is it cut to that length, so no\n * part of a secret survives at the edge. A redirect is refused rather than\n * followed: the credential headers would go with it to wherever it points.\n */\nexport async function post(provider: string, url: string, init: { headers: Record<string, string>; body: string }, secrets: (string | undefined)[] = []): Promise<Response> {\n const response = await fetch(url, { method: \"POST\", headers: init.headers, body: init.body, redirect: \"error\", signal: AbortSignal.timeout(TIMEOUT_MS) });\n if (!response.ok) {\n let text = \"\";\n try {\n text = await response.text();\n } catch {\n // The status is enough.\n }\n throw new Error(`${provider} ${origin(url)} answered ${response.status}${text ? `: ${errorBody(text, secrets)}` : \"\"}`);\n }\n return response;\n}\n\n/** The start of an error body, secrets cut out first, then cut to ERROR_BODY_MAX on a code point. */\nexport function errorBody(text: string, secrets: (string | undefined)[] = []): string {\n const kept = secrets.filter((s): s is string => typeof s === \"string\" && s.length >= 4);\n const longest = kept.reduce((n, s) => Math.max(n, s.length), 0);\n let head = cut(text, ERROR_BODY_MAX + longest);\n for (const secret of kept) head = head.split(secret).join(\"[redacted]\");\n return cut(head, ERROR_BODY_MAX);\n}\n\n/** A credential with the spaces and newlines a paste leaves around it taken off. Anything not a string is empty. */\nexport function trimmed(value: unknown): string {\n return typeof value === \"string\" ? value.trim() : \"\";\n}\n\n/** Base64 of UTF-8, without Buffer. */\nexport function base64(text: string): string {\n let binary = \"\";\n for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nexport function basicAuth(user: string, password: string): string {\n return `Basic ${base64(`${user}:${password}`)}`;\n}\n\nexport function hex(bytes: ArrayBuffer | Uint8Array): string {\n return Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function sha256Hex(text: string): Promise<string> {\n return hex(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text)));\n}\n\n/**\n * A stable 32 hex character id for one alert: the same job, type and time\n * always give the same id, so a provider that deduplicates on it drops a\n * resend of an alert it already took.\n */\nexport async function alertId(alert: Alert): Promise<string> {\n return (await sha256Hex(`${alert.job}\\n${alert.type}\\n${alert.at}`)).slice(0, 32);\n}\n\n/** The same id laid out as a UUID, for APIs that ask for one. */\nexport function asUuid(id: string): string {\n return `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20, 32)}`;\n}\n\n/** Cuts to at most `max` UTF-16 units without splitting a surrogate pair. */\nexport function cut(text: string, max: number): string {\n if (text.length <= max) return text;\n let end = max;\n const code = text.charCodeAt(end - 1);\n if (code >= 0xd800 && code <= 0xdbff) end -= 1;\n return text.slice(0, end);\n}\n\n/** The run fields worth attaching to a tracker event. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Datadog Events API v1.\n * API reference: https://docs.datadoghq.com/api/latest/events/ (Post an event)\n * Field limits: https://datadoghq.dev/datadog-api-client-typescript/classes/v1.EventCreateRequest.html\n * POST https://api.<site>/api/v1/events with DD-API-KEY. Answers 202.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, plainText, post, sha256Hex, trimmed } from \"./shared.js\";\n\nexport interface DatadogOptions {\n /** An API key (not an application key). */\n apiKey: string;\n /** Your Datadog site: \"datadoghq.com\" (the default), \"datadoghq.eu\", \"us3.datadoghq.com\", \"us5.datadoghq.com\", \"ap1.datadoghq.com\", \"ddog-gov.com\". */\n site?: string;\n /** Extra tags, \"env:prod\" say. Every event also has cronwatch, job:<name> and alert:<type>. */\n tags?: string[];\n /** Associates the event with a host and its tags. */\n host?: string;\n link?: (alert: Alert) => string;\n}\n\nconst ALERT_TYPE: Record<Alert[\"type\"], \"error\" | \"warning\" | \"success\"> = {\n missed: \"error\",\n failed: \"error\",\n stuck: \"error\",\n slow: \"warning\",\n over_budget: \"warning\",\n recovered: \"success\",\n};\n\n/** Posts alerts to the Datadog event stream, aggregated per job and alert type. */\nexport function datadog(options: DatadogOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"datadog() needs an apiKey\");\n const site = (options.site ?? \"datadoghq.com\").replace(/^https?:\\/\\//, \"\").replace(/^(api|app)\\./, \"\").replace(/\\/+$/, \"\");\n if (!/^[a-z0-9.-]+$/i.test(site)) throw new Error(\"datadog() needs a site like datadoghq.com\");\n const url = `https://api.${site}/api/v1/events`;\n return {\n name: \"datadog\",\n async send(alert) {\n const link = options.link?.(alert);\n const event = {\n title: cut(alert.title, 500),\n text: cut(plainText(alert, link), 4000),\n alert_type: ALERT_TYPE[alert.type],\n aggregation_key: await aggregationKey(alert),\n date_happened: Math.floor(alert.at / 1000),\n priority: \"normal\",\n tags: [\"cronwatch\", `job:${alert.job}`, `alert:${alert.type}`, ...(options.tags ?? [])],\n ...(options.host ? { host: options.host } : {}),\n };\n await post(\"Datadog\", url, {\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"dd-api-key\": apiKey },\n body: JSON.stringify(event),\n }, [apiKey]);\n },\n };\n}\n\n/** \"cronwatch:<job>:<type>\", or a hash of it when that passes Datadog's 100 characters. */\nasync function aggregationKey(alert: Alert): Promise<string> {\n const key = `cronwatch:${alert.job}:${alert.type}`;\n return key.length <= 100 ? key : `cronwatch:${(await sha256Hex(key)).slice(0, 40)}`;\n}\n"]}
1
+ {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/datadog.ts"],"names":[],"mappings":";;;AAOO,IAAM,UAAA,GAAa,GAAA;AAYnB,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI;AACF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AAoB,cAAc,MAAA,EAAO;AAAA,QAChG,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,KAAK;AAAA,OAC5B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF;AAGA,eAAe,eAAe,KAAA,EAA+B;AAC3D,EAAA,MAAM,MAAM,CAAA,UAAA,EAAa,KAAA,CAAM,GAAG,CAAA,CAAA,EAAI,MAAM,IAAI,CAAA,CAAA;AAChD,EAAA,OAAO,GAAA,CAAI,MAAA,IAAU,GAAA,GAAM,GAAA,GAAM,CAAA,UAAA,EAAA,CAAc,MAAM,SAAA,CAAU,GAAG,CAAA,EAAG,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA;AACnF","file":"datadog.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 type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/**\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. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Datadog Events API v1.\n * API reference: https://docs.datadoghq.com/api/latest/events/ (Post an event)\n * Field limits: https://datadoghq.dev/datadog-api-client-typescript/classes/v1.EventCreateRequest.html\n * POST https://api.<site>/api/v1/events with DD-API-KEY. Answers 202.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, plainText, post, sha256Hex, trimmed } from \"./shared.js\";\n\nexport interface DatadogOptions {\n /** An API key (not an application key). */\n apiKey: string;\n /** Your Datadog site: \"datadoghq.com\" (the default), \"datadoghq.eu\", \"us3.datadoghq.com\", \"us5.datadoghq.com\", \"ap1.datadoghq.com\", \"ddog-gov.com\". */\n site?: string;\n /** Extra tags, \"env:prod\" say. Every event also has cronwatch, job:<name> and alert:<type>. */\n tags?: string[];\n /** Associates the event with a host and its tags. */\n host?: string;\n link?: (alert: Alert) => string;\n}\n\nconst ALERT_TYPE: Record<Alert[\"type\"], \"error\" | \"warning\" | \"success\"> = {\n missed: \"error\",\n failed: \"error\",\n stuck: \"error\",\n slow: \"warning\",\n over_budget: \"warning\",\n recovered: \"success\",\n};\n\n/** Posts alerts to the Datadog event stream, aggregated per job and alert type. */\nexport function datadog(options: DatadogOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"datadog() needs an apiKey\");\n const site = (options.site ?? \"datadoghq.com\").replace(/^https?:\\/\\//, \"\").replace(/^(api|app)\\./, \"\").replace(/\\/+$/, \"\");\n if (!/^[a-z0-9.-]+$/i.test(site)) throw new Error(\"datadog() needs a site like datadoghq.com\");\n const url = `https://api.${site}/api/v1/events`;\n return {\n name: \"datadog\",\n async send(alert) {\n const link = options.link?.(alert);\n const event = {\n title: cut(alert.title, 500),\n text: cut(plainText(alert, link), 4000),\n alert_type: ALERT_TYPE[alert.type],\n aggregation_key: await aggregationKey(alert),\n date_happened: Math.floor(alert.at / 1000),\n priority: \"normal\",\n tags: [\"cronwatch\", `job:${alert.job}`, `alert:${alert.type}`, ...(options.tags ?? [])],\n ...(options.host ? { host: options.host } : {}),\n };\n await post(\"Datadog\", url, {\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"dd-api-key\": apiKey },\n body: JSON.stringify(event),\n }, [apiKey]);\n },\n };\n}\n\n/** \"cronwatch:<job>:<type>\", or a hash of it when that passes Datadog's 100 characters. */\nasync function aggregationKey(alert: Alert): Promise<string> {\n const key = `cronwatch:${alert.job}:${alert.type}`;\n return key.length <= 100 ? key : `cronwatch:${(await sha256Hex(key)).slice(0, 40)}`;\n}\n"]}
package/dist/datadog.js CHANGED
@@ -7,9 +7,19 @@ function origin(url) {
7
7
  return "(invalid URL)";
8
8
  }
9
9
  }
10
+ function postable(url) {
11
+ let protocol;
12
+ try {
13
+ protocol = new URL(url).protocol;
14
+ } catch {
15
+ throw new Error("only http and https URLs can be posted to, not this URL");
16
+ }
17
+ if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
18
+ return url;
19
+ }
10
20
  var ERROR_BODY_MAX = 200;
11
21
  async function post(provider, url, init, secrets = []) {
12
- const response = await fetch(url, { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
22
+ const response = await fetch(postable(url), { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
13
23
  if (!response.ok) {
14
24
  let text = "";
15
25
  try {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/datadog.ts"],"names":[],"mappings":";AAOO,IAAM,UAAA,GAAa,GAAA;AAYnB,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,MAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,eAAA;AAAA,EACT;AACF;AAGO,IAAM,cAAA,GAAiB,GAAA;AAW9B,eAAsB,KAAK,QAAA,EAAkB,GAAA,EAAa,IAAA,EAAyD,OAAA,GAAkC,EAAC,EAAsB;AAC1K,EAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,GAAA,EAAK,EAAE,MAAA,EAAQ,MAAA,EAAQ,SAAS,IAAA,CAAK,OAAA,EAAS,MAAM,IAAA,CAAK,IAAA,EAAM,UAAU,OAAA,EAAS,MAAA,EAAQ,YAAY,OAAA,CAAQ,UAAU,GAAG,CAAA;AACxJ,EAAA,IAAI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,EAAO,MAAM,GAAG,CAAA,CAAA,EAAI,CAAA,MAAA,EAAS,KAAA,CAAM,IAAI,CAAA,CAAA,EAAI,GAAI,OAAA,CAAQ,IAAA,IAAQ,EAAG,CAAA;AAAA,QACtF,GAAI,QAAQ,IAAA,GAAO,EAAE,MAAM,OAAA,CAAQ,IAAA,KAAS;AAAC,OAC/C;AACA,MAAA,MAAM,IAAA,CAAK,WAAW,GAAA,EAAK;AAAA,QACzB,SAAS,EAAE,cAAA,EAAgB,oBAAoB,MAAA,EAAQ,kBAAA,EAAoB,cAAc,MAAA,EAAO;AAAA,QAChG,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,KAAK;AAAA,OAC5B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF;AAGA,eAAe,eAAe,KAAA,EAA+B;AAC3D,EAAA,MAAM,MAAM,CAAA,UAAA,EAAa,KAAA,CAAM,GAAG,CAAA,CAAA,EAAI,MAAM,IAAI,CAAA,CAAA;AAChD,EAAA,OAAO,GAAA,CAAI,MAAA,IAAU,GAAA,GAAM,GAAA,GAAM,CAAA,UAAA,EAAA,CAAc,MAAM,SAAA,CAAU,GAAG,CAAA,EAAG,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA;AACnF","file":"datadog.js","sourcesContent":["/**\n * Helpers shared by the provider channels. Only fetch and Web Crypto, so the\n * channels run on Node, Cloudflare Workers, Deno and Bun alike. Not an entry\n * point: each channel bundles its own copy.\n */\nimport type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/** How much of a provider's error body goes into the error message. */\nexport const ERROR_BODY_MAX = 200;\n\n/**\n * POSTs and throws on a non-2xx answer. The error names the provider and the\n * URL's origin, plus the start of the response body with every secret the\n * channel holds cut out, in case a provider echoes one back. Secrets are cut\n * from a prefix long enough to hold one that starts inside the first\n * ERROR_BODY_MAX characters, and only then is it cut to that length, so no\n * part of a secret survives at the edge. A redirect is refused rather than\n * followed: the credential headers would go with it to wherever it points.\n */\nexport async function post(provider: string, url: string, init: { headers: Record<string, string>; body: string }, secrets: (string | undefined)[] = []): Promise<Response> {\n const response = await fetch(url, { method: \"POST\", headers: init.headers, body: init.body, redirect: \"error\", signal: AbortSignal.timeout(TIMEOUT_MS) });\n if (!response.ok) {\n let text = \"\";\n try {\n text = await response.text();\n } catch {\n // The status is enough.\n }\n throw new Error(`${provider} ${origin(url)} answered ${response.status}${text ? `: ${errorBody(text, secrets)}` : \"\"}`);\n }\n return response;\n}\n\n/** The start of an error body, secrets cut out first, then cut to ERROR_BODY_MAX on a code point. */\nexport function errorBody(text: string, secrets: (string | undefined)[] = []): string {\n const kept = secrets.filter((s): s is string => typeof s === \"string\" && s.length >= 4);\n const longest = kept.reduce((n, s) => Math.max(n, s.length), 0);\n let head = cut(text, ERROR_BODY_MAX + longest);\n for (const secret of kept) head = head.split(secret).join(\"[redacted]\");\n return cut(head, ERROR_BODY_MAX);\n}\n\n/** A credential with the spaces and newlines a paste leaves around it taken off. Anything not a string is empty. */\nexport function trimmed(value: unknown): string {\n return typeof value === \"string\" ? value.trim() : \"\";\n}\n\n/** Base64 of UTF-8, without Buffer. */\nexport function base64(text: string): string {\n let binary = \"\";\n for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nexport function basicAuth(user: string, password: string): string {\n return `Basic ${base64(`${user}:${password}`)}`;\n}\n\nexport function hex(bytes: ArrayBuffer | Uint8Array): string {\n return Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function sha256Hex(text: string): Promise<string> {\n return hex(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text)));\n}\n\n/**\n * A stable 32 hex character id for one alert: the same job, type and time\n * always give the same id, so a provider that deduplicates on it drops a\n * resend of an alert it already took.\n */\nexport async function alertId(alert: Alert): Promise<string> {\n return (await sha256Hex(`${alert.job}\\n${alert.type}\\n${alert.at}`)).slice(0, 32);\n}\n\n/** The same id laid out as a UUID, for APIs that ask for one. */\nexport function asUuid(id: string): string {\n return `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20, 32)}`;\n}\n\n/** Cuts to at most `max` UTF-16 units without splitting a surrogate pair. */\nexport function cut(text: string, max: number): string {\n if (text.length <= max) return text;\n let end = max;\n const code = text.charCodeAt(end - 1);\n if (code >= 0xd800 && code <= 0xdbff) end -= 1;\n return text.slice(0, end);\n}\n\n/** The run fields worth attaching to a tracker event. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Datadog Events API v1.\n * API reference: https://docs.datadoghq.com/api/latest/events/ (Post an event)\n * Field limits: https://datadoghq.dev/datadog-api-client-typescript/classes/v1.EventCreateRequest.html\n * POST https://api.<site>/api/v1/events with DD-API-KEY. Answers 202.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, plainText, post, sha256Hex, trimmed } from \"./shared.js\";\n\nexport interface DatadogOptions {\n /** An API key (not an application key). */\n apiKey: string;\n /** Your Datadog site: \"datadoghq.com\" (the default), \"datadoghq.eu\", \"us3.datadoghq.com\", \"us5.datadoghq.com\", \"ap1.datadoghq.com\", \"ddog-gov.com\". */\n site?: string;\n /** Extra tags, \"env:prod\" say. Every event also has cronwatch, job:<name> and alert:<type>. */\n tags?: string[];\n /** Associates the event with a host and its tags. */\n host?: string;\n link?: (alert: Alert) => string;\n}\n\nconst ALERT_TYPE: Record<Alert[\"type\"], \"error\" | \"warning\" | \"success\"> = {\n missed: \"error\",\n failed: \"error\",\n stuck: \"error\",\n slow: \"warning\",\n over_budget: \"warning\",\n recovered: \"success\",\n};\n\n/** Posts alerts to the Datadog event stream, aggregated per job and alert type. */\nexport function datadog(options: DatadogOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"datadog() needs an apiKey\");\n const site = (options.site ?? \"datadoghq.com\").replace(/^https?:\\/\\//, \"\").replace(/^(api|app)\\./, \"\").replace(/\\/+$/, \"\");\n if (!/^[a-z0-9.-]+$/i.test(site)) throw new Error(\"datadog() needs a site like datadoghq.com\");\n const url = `https://api.${site}/api/v1/events`;\n return {\n name: \"datadog\",\n async send(alert) {\n const link = options.link?.(alert);\n const event = {\n title: cut(alert.title, 500),\n text: cut(plainText(alert, link), 4000),\n alert_type: ALERT_TYPE[alert.type],\n aggregation_key: await aggregationKey(alert),\n date_happened: Math.floor(alert.at / 1000),\n priority: \"normal\",\n tags: [\"cronwatch\", `job:${alert.job}`, `alert:${alert.type}`, ...(options.tags ?? [])],\n ...(options.host ? { host: options.host } : {}),\n };\n await post(\"Datadog\", url, {\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"dd-api-key\": apiKey },\n body: JSON.stringify(event),\n }, [apiKey]);\n },\n };\n}\n\n/** \"cronwatch:<job>:<type>\", or a hash of it when that passes Datadog's 100 characters. */\nasync function aggregationKey(alert: Alert): Promise<string> {\n const key = `cronwatch:${alert.job}:${alert.type}`;\n return key.length <= 100 ? key : `cronwatch:${(await sha256Hex(key)).slice(0, 40)}`;\n}\n"]}
1
+ {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/datadog.ts"],"names":[],"mappings":";AAOO,IAAM,UAAA,GAAa,GAAA;AAYnB,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,MAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,eAAA;AAAA,EACT;AACF;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,EAAC,EAAsB;AAC1K,EAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,QAAA,CAAS,GAAG,CAAA,EAAG,EAAE,MAAA,EAAQ,MAAA,EAAQ,OAAA,EAAS,IAAA,CAAK,SAAS,IAAA,EAAM,IAAA,CAAK,MAAM,QAAA,EAAU,OAAA,EAAS,QAAQ,WAAA,CAAY,OAAA,CAAQ,UAAU,CAAA,EAAG,CAAA;AAClK,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,IAAI,IAAA,GAAO,EAAA;AACX,IAAA,IAAI;AACF,MAAA,IAAA,GAAO,MAA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AAQ,IAAA,IAAQ,EAAG,CAAA;AAAA,QACtF,GAAI,QAAQ,IAAA,GAAO,EAAE,MAAM,OAAA,CAAQ,IAAA,KAAS;AAAC,OAC/C;AACA,MAAA,MAAM,IAAA,CAAK,WAAW,GAAA,EAAK;AAAA,QACzB,SAAS,EAAE,cAAA,EAAgB,oBAAoB,MAAA,EAAQ,kBAAA,EAAoB,cAAc,MAAA,EAAO;AAAA,QAChG,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,KAAK;AAAA,OAC5B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF;AAGA,eAAe,eAAe,KAAA,EAA+B;AAC3D,EAAA,MAAM,MAAM,CAAA,UAAA,EAAa,KAAA,CAAM,GAAG,CAAA,CAAA,EAAI,MAAM,IAAI,CAAA,CAAA;AAChD,EAAA,OAAO,GAAA,CAAI,MAAA,IAAU,GAAA,GAAM,GAAA,GAAM,CAAA,UAAA,EAAA,CAAc,MAAM,SAAA,CAAU,GAAG,CAAA,EAAG,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA;AACnF","file":"datadog.js","sourcesContent":["/**\n * Helpers shared by the provider channels. Only fetch and Web Crypto, so the\n * channels run on Node, Cloudflare Workers, Deno and Bun alike. Not an entry\n * point: each channel bundles its own copy.\n */\nimport type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/**\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. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Datadog Events API v1.\n * API reference: https://docs.datadoghq.com/api/latest/events/ (Post an event)\n * Field limits: https://datadoghq.dev/datadog-api-client-typescript/classes/v1.EventCreateRequest.html\n * POST https://api.<site>/api/v1/events with DD-API-KEY. Answers 202.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, plainText, post, sha256Hex, trimmed } from \"./shared.js\";\n\nexport interface DatadogOptions {\n /** An API key (not an application key). */\n apiKey: string;\n /** Your Datadog site: \"datadoghq.com\" (the default), \"datadoghq.eu\", \"us3.datadoghq.com\", \"us5.datadoghq.com\", \"ap1.datadoghq.com\", \"ddog-gov.com\". */\n site?: string;\n /** Extra tags, \"env:prod\" say. Every event also has cronwatch, job:<name> and alert:<type>. */\n tags?: string[];\n /** Associates the event with a host and its tags. */\n host?: string;\n link?: (alert: Alert) => string;\n}\n\nconst ALERT_TYPE: Record<Alert[\"type\"], \"error\" | \"warning\" | \"success\"> = {\n missed: \"error\",\n failed: \"error\",\n stuck: \"error\",\n slow: \"warning\",\n over_budget: \"warning\",\n recovered: \"success\",\n};\n\n/** Posts alerts to the Datadog event stream, aggregated per job and alert type. */\nexport function datadog(options: DatadogOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"datadog() needs an apiKey\");\n const site = (options.site ?? \"datadoghq.com\").replace(/^https?:\\/\\//, \"\").replace(/^(api|app)\\./, \"\").replace(/\\/+$/, \"\");\n if (!/^[a-z0-9.-]+$/i.test(site)) throw new Error(\"datadog() needs a site like datadoghq.com\");\n const url = `https://api.${site}/api/v1/events`;\n return {\n name: \"datadog\",\n async send(alert) {\n const link = options.link?.(alert);\n const event = {\n title: cut(alert.title, 500),\n text: cut(plainText(alert, link), 4000),\n alert_type: ALERT_TYPE[alert.type],\n aggregation_key: await aggregationKey(alert),\n date_happened: Math.floor(alert.at / 1000),\n priority: \"normal\",\n tags: [\"cronwatch\", `job:${alert.job}`, `alert:${alert.type}`, ...(options.tags ?? [])],\n ...(options.host ? { host: options.host } : {}),\n };\n await post(\"Datadog\", url, {\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"dd-api-key\": apiKey },\n body: JSON.stringify(event),\n }, [apiKey]);\n },\n };\n}\n\n/** \"cronwatch:<job>:<type>\", or a hash of it when that passes Datadog's 100 characters. */\nasync function aggregationKey(alert: Alert): Promise<string> {\n const key = `cronwatch:${alert.job}:${alert.type}`;\n return key.length <= 100 ? key : `cronwatch:${(await sha256Hex(key)).slice(0, 40)}`;\n}\n"]}
package/dist/discord.cjs CHANGED
@@ -1,5 +1,17 @@
1
1
  'use strict';
2
2
 
3
+ // src/alerts/shared.ts
4
+ function postable(url) {
5
+ let protocol;
6
+ try {
7
+ protocol = new URL(url).protocol;
8
+ } catch {
9
+ throw new Error("only http and https URLs can be posted to, not this URL");
10
+ }
11
+ if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
12
+ return url;
13
+ }
14
+
3
15
  // src/alerts/discord.ts
4
16
  var COLOR = {
5
17
  missed: 12024095,
@@ -16,7 +28,7 @@ function discord(options) {
16
28
  name: "discord",
17
29
  async send(alert) {
18
30
  const url = options.link?.(alert);
19
- const response = await fetch(options.webhookUrl, {
31
+ const response = await fetch(postable(options.webhookUrl), {
20
32
  method: "POST",
21
33
  headers: { "content-type": "application/json" },
22
34
  // Refused, not followed: a webhook URL is its own credential.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/alerts/discord.ts"],"names":[],"mappings":";;;AAQA,IAAM,KAAA,GAAuC;AAAA,EAC3C,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ,QAAA;AAAA,EACR,KAAA,EAAO,QAAA;AAAA,EACP,IAAA,EAAM,QAAA;AAAA,EACN,WAAA,EAAa,QAAA;AAAA,EACb,SAAA,EAAW;AACb,CAAA;AAEA,IAAM,UAAA,GAAa,GAAA;AAGZ,SAAS,QAAQ,OAAA,EAAuC;AAC7D,EAAA,IAAI,CAAC,OAAA,CAAQ,UAAA,EAAY,MAAM,IAAI,MAAM,8BAA8B,CA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AM,MAAM,SAAS,IAAA,EAAK,EAAG,MAAM,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,CAAA;AAAA,IAC3H;AAAA,GACF;AACF;AAGO,SAAS,cAAc,IAAA,EAAsB;AAClD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,MAAA,EAAQ,iBAAO,CAAA;AACrC;AAGO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,mBAAA,EAAqB,MAAM,CAAA;AACjD","file":"discord.cjs","sourcesContent":["import type { Alert, AlertChannel } from \"../types.js\";\n\nexport interface DiscordOptions {\n /** A channel webhook URL from Server Settings, Integrations, Webhooks. */\n webhookUrl: string;\n link?: (alert: Alert) => string;\n}\n\nconst COLOR: Record<Alert[\"type\"], number> = {\n missed: 0xb7791f,\n failed: 0xc62828,\n stuck: 0xc62828,\n slow: 0xb7791f,\n over_budget: 0xb7791f,\n recovered: 0x1f8a4c,\n};\n\nconst TIMEOUT_MS = 10_000;\n\n/** Sends alerts to a Discord channel through a webhook. */\nexport function discord(options: DiscordOptions): AlertChannel {\n if (!options.webhookUrl) throw new Error(\"discord() needs a webhookUrl\");\n return {\n name: \"discord\",\n async send(alert) {\n const url = options.link?.(alert);\n const response = await fetch(options.webhookUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n // Refused, not followed: a webhook URL is its own credential.\n redirect: \"error\",\n signal: AbortSignal.timeout(TIMEOUT_MS),\n body: JSON.stringify({\n content: alert.title,\n // Job output can hold anything, \"@everyone\" included; ping no one.\n allowed_mentions: { parse: [] },\n embeds: [\n {\n title: alert.title,\n ...(url ? { url } : {}),\n description: \"```\\n\" + codeBlockSafe(alert.message.slice(0, 3800)) + \"\\n```\" + (alert.triage ? `\\n**Triage:** ${escapeMarkdown(alert.triage.slice(0, 1000))}` : \"\"),\n color: COLOR[alert.type],\n timestamp: new Date(alert.at).toISOString(),\n },\n ],\n }),\n });\n if (!response.ok) throw new Error(`Discord webhook answered ${response.status}: ${(await response.text()).slice(0, 200)}`);\n },\n };\n}\n\n/** Breaks up ``` so text inside a code block cannot close it. */\nexport function codeBlockSafe(text: string): string {\n return text.replace(/```/g, \"`​`​`\");\n}\n\n/** Escapes the characters Discord reads as markdown, links included. */\nexport function escapeMarkdown(text: string): string {\n return text.replace(/[\\\\`*_~|[\\]()<>]/g, \"\\\\$&\");\n}\n"]}
1
+ {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/discord.ts"],"names":[],"mappings":";;;AAgCO,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;;;AChCA,IAAM,KAAA,GAAuC;AAAA,EAC3C,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ,QAAA;AAAA,EACR,KAAA,EAAO,QAAA;AAAA,EACP,IAAA,EAAM,QAAA;AAAA,EACN,WAAA,EAAa,QAAA;AAAA,EACb,SAAA,EAAW;AACb,CAAA;AAEA,IAAM,UAAA,GAAa,GAAA;AAGZ,SAAS,QAAQ,OAAA,EAAuC;AAC7D,EAAA,IAAI,CAAC,OAAA,CAAQ,UAAA,EAAY,MAAM,IAAI,MAAM,8BAA8B,CAAA;AACvE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,SAAA;AAAA,IACN,MAAM,KAAK,KAAA,EAAO;AAChB,MAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,IAAA,GAAO,KAAK,CAAA;AAChC,MAAA,MAAM,W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AAA,CAAK,OAAA,CAAQ,MAAA,EAAQ,iBAAO,CAAA;AACrC;AAGO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,mBAAA,EAAqB,MAAM,CAAA;AACjD","file":"discord.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 type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/**\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. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","import type { Alert, AlertChannel } from \"../types.js\";\nimport { postable } from \"./shared.js\";\n\nexport interface DiscordOptions {\n /** A channel webhook URL from Server Settings, Integrations, Webhooks. */\n webhookUrl: string;\n link?: (alert: Alert) => string;\n}\n\nconst COLOR: Record<Alert[\"type\"], number> = {\n missed: 0xb7791f,\n failed: 0xc62828,\n stuck: 0xc62828,\n slow: 0xb7791f,\n over_budget: 0xb7791f,\n recovered: 0x1f8a4c,\n};\n\nconst TIMEOUT_MS = 10_000;\n\n/** Sends alerts to a Discord channel through a webhook. */\nexport function discord(options: DiscordOptions): AlertChannel {\n if (!options.webhookUrl) throw new Error(\"discord() needs a webhookUrl\");\n return {\n name: \"discord\",\n async send(alert) {\n const url = options.link?.(alert);\n const response = await fetch(postable(options.webhookUrl), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n // Refused, not followed: a webhook URL is its own credential.\n redirect: \"error\",\n signal: AbortSignal.timeout(TIMEOUT_MS),\n body: JSON.stringify({\n content: alert.title,\n // Job output can hold anything, \"@everyone\" included; ping no one.\n allowed_mentions: { parse: [] },\n embeds: [\n {\n title: alert.title,\n ...(url ? { url } : {}),\n description: \"```\\n\" + codeBlockSafe(alert.message.slice(0, 3800)) + \"\\n```\" + (alert.triage ? `\\n**Triage:** ${escapeMarkdown(alert.triage.slice(0, 1000))}` : \"\"),\n color: COLOR[alert.type],\n timestamp: new Date(alert.at).toISOString(),\n },\n ],\n }),\n });\n if (!response.ok) throw new Error(`Discord webhook answered ${response.status}: ${(await response.text()).slice(0, 200)}`);\n },\n };\n}\n\n/** Breaks up ``` so text inside a code block cannot close it. */\nexport function codeBlockSafe(text: string): string {\n return text.replace(/```/g, \"`​`​`\");\n}\n\n/** Escapes the characters Discord reads as markdown, links included. */\nexport function escapeMarkdown(text: string): string {\n return text.replace(/[\\\\`*_~|[\\]()<>]/g, \"\\\\$&\");\n}\n"]}
package/dist/discord.js CHANGED
@@ -1,3 +1,15 @@
1
+ // src/alerts/shared.ts
2
+ function postable(url) {
3
+ let protocol;
4
+ try {
5
+ protocol = new URL(url).protocol;
6
+ } catch {
7
+ throw new Error("only http and https URLs can be posted to, not this URL");
8
+ }
9
+ if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
10
+ return url;
11
+ }
12
+
1
13
  // src/alerts/discord.ts
2
14
  var COLOR = {
3
15
  missed: 12024095,
@@ -14,7 +26,7 @@ function discord(options) {
14
26
  name: "discord",
15
27
  async send(alert) {
16
28
  const url = options.link?.(alert);
17
- const response = await fetch(options.webhookUrl, {
29
+ const response = await fetch(postable(options.webhookUrl), {
18
30
  method: "POST",
19
31
  headers: { "content-type": "application/json" },
20
32
  // Refused, not followed: a webhook URL is its own credential.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/alerts/discord.ts"],"names":[],"mappings":";AAQA,IAAM,KAAA,GAAuC;AAAA,EAC3C,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ,QAAA;AAAA,EACR,K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AA,CAAM,KAAA,CAAM,IAAI,CAAA;AAAA,cACvB,WAAW,IAAI,IAAA,CAAK,KAAA,CAAM,EAAE,EAAE,WAAA;AAAY;AAC5C;AACF,SACD;AAAA,OACF,CAAA;AACD,MAAA,IAAI,CAAC,QAAA,CAAS,EAAA,QAAU,IAAI,KAAA,CAAM,4BAA4B,QAAA,CAAS,MAAM,CAAA,EAAA,EAAA,CAAM,MAAM,SAAS,IAAA,EAAK,EAAG,MAAM,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,CAAA;AAAA,IAC3H;AAAA,GACF;AACF;AAGO,SAAS,cAAc,IAAA,EAAsB;AAClD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,MAAA,EAAQ,iBAAO,CAAA;AACrC;AAGO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,mBAAA,EAAqB,MAAM,CAAA;AACjD","file":"discord.js","sourcesContent":["import type { Alert, AlertChannel } from \"../types.js\";\n\nexport interface DiscordOptions {\n /** A channel webhook URL from Server Settings, Integrations, Webhooks. */\n webhookUrl: string;\n link?: (alert: Alert) => string;\n}\n\nconst COLOR: Record<Alert[\"type\"], number> = {\n missed: 0xb7791f,\n failed: 0xc62828,\n stuck: 0xc62828,\n slow: 0xb7791f,\n over_budget: 0xb7791f,\n recovered: 0x1f8a4c,\n};\n\nconst TIMEOUT_MS = 10_000;\n\n/** Sends alerts to a Discord channel through a webhook. */\nexport function discord(options: DiscordOptions): AlertChannel {\n if (!options.webhookUrl) throw new Error(\"discord() needs a webhookUrl\");\n return {\n name: \"discord\",\n async send(alert) {\n const url = options.link?.(alert);\n const response = await fetch(options.webhookUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n // Refused, not followed: a webhook URL is its own credential.\n redirect: \"error\",\n signal: AbortSignal.timeout(TIMEOUT_MS),\n body: JSON.stringify({\n content: alert.title,\n // Job output can hold anything, \"@everyone\" included; ping no one.\n allowed_mentions: { parse: [] },\n embeds: [\n {\n title: alert.title,\n ...(url ? { url } : {}),\n description: \"```\\n\" + codeBlockSafe(alert.message.slice(0, 3800)) + \"\\n```\" + (alert.triage ? `\\n**Triage:** ${escapeMarkdown(alert.triage.slice(0, 1000))}` : \"\"),\n color: COLOR[alert.type],\n timestamp: new Date(alert.at).toISOString(),\n },\n ],\n }),\n });\n if (!response.ok) throw new Error(`Discord webhook answered ${response.status}: ${(await response.text()).slice(0, 200)}`);\n },\n };\n}\n\n/** Breaks up ``` so text inside a code block cannot close it. */\nexport function codeBlockSafe(text: string): string {\n return text.replace(/```/g, \"`​`​`\");\n}\n\n/** Escapes the characters Discord reads as markdown, links included. */\nexport function escapeMarkdown(text: string): string {\n return text.replace(/[\\\\`*_~|[\\]()<>]/g, \"\\\\$&\");\n}\n"]}
1
+ {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/discord.ts"],"names":[],"mappings":";AAgCO,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;;;AChCA,IAAM,KAAA,GAAuC;AAAA,EAC3C,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ,QAAA;AAAA,EACR,KAAA,EAAO,QAAA;AAAA,EACP,IAAA,EAAM,QAAA;AAAA,EACN,WAAA,EAAa,QAAA;AAAA,EACb,SAAA,EAAW;AACb,CAAA;AAEA,IAAM,UAAA,GAAa,GAAA;AAGZ,SAAS,QAAQ,OAAA,EAAuC;AAC7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A,CAAS,EAAA,QAAU,IAAI,KAAA,CAAM,4BAA4B,QAAA,CAAS,MAAM,CAAA,EAAA,EAAA,CAAM,MAAM,SAAS,IAAA,EAAK,EAAG,MAAM,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,CAAA;AAAA,IAC3H;AAAA,GACF;AACF;AAGO,SAAS,cAAc,IAAA,EAAsB;AAClD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,MAAA,EAAQ,iBAAO,CAAA;AACrC;AAGO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,mBAAA,EAAqB,MAAM,CAAA;AACjD","file":"discord.js","sourcesContent":["/**\n * Helpers shared by the provider channels. Only fetch and Web Crypto, so the\n * channels run on Node, Cloudflare Workers, Deno and Bun alike. Not an entry\n * point: each channel bundles its own copy.\n */\nimport type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/**\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. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","import type { Alert, AlertChannel } from \"../types.js\";\nimport { postable } from \"./shared.js\";\n\nexport interface DiscordOptions {\n /** A channel webhook URL from Server Settings, Integrations, Webhooks. */\n webhookUrl: string;\n link?: (alert: Alert) => string;\n}\n\nconst COLOR: Record<Alert[\"type\"], number> = {\n missed: 0xb7791f,\n failed: 0xc62828,\n stuck: 0xc62828,\n slow: 0xb7791f,\n over_budget: 0xb7791f,\n recovered: 0x1f8a4c,\n};\n\nconst TIMEOUT_MS = 10_000;\n\n/** Sends alerts to a Discord channel through a webhook. */\nexport function discord(options: DiscordOptions): AlertChannel {\n if (!options.webhookUrl) throw new Error(\"discord() needs a webhookUrl\");\n return {\n name: \"discord\",\n async send(alert) {\n const url = options.link?.(alert);\n const response = await fetch(postable(options.webhookUrl), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n // Refused, not followed: a webhook URL is its own credential.\n redirect: \"error\",\n signal: AbortSignal.timeout(TIMEOUT_MS),\n body: JSON.stringify({\n content: alert.title,\n // Job output can hold anything, \"@everyone\" included; ping no one.\n allowed_mentions: { parse: [] },\n embeds: [\n {\n title: alert.title,\n ...(url ? { url } : {}),\n description: \"```\\n\" + codeBlockSafe(alert.message.slice(0, 3800)) + \"\\n```\" + (alert.triage ? `\\n**Triage:** ${escapeMarkdown(alert.triage.slice(0, 1000))}` : \"\"),\n color: COLOR[alert.type],\n timestamp: new Date(alert.at).toISOString(),\n },\n ],\n }),\n });\n if (!response.ok) throw new Error(`Discord webhook answered ${response.status}: ${(await response.text()).slice(0, 200)}`);\n },\n };\n}\n\n/** Breaks up ``` so text inside a code block cannot close it. */\nexport function codeBlockSafe(text: string): string {\n return text.replace(/```/g, \"`​`​`\");\n}\n\n/** Escapes the characters Discord reads as markdown, links included. */\nexport function escapeMarkdown(text: string): string {\n return text.replace(/[\\\\`*_~|[\\]()<>]/g, \"\\\\$&\");\n}\n"]}
@@ -9,9 +9,19 @@ function origin(url) {
9
9
  return "(invalid URL)";
10
10
  }
11
11
  }
12
+ function postable(url) {
13
+ let protocol;
14
+ try {
15
+ protocol = new URL(url).protocol;
16
+ } catch {
17
+ throw new Error("only http and https URLs can be posted to, not this URL");
18
+ }
19
+ if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
20
+ return url;
21
+ }
12
22
  var ERROR_BODY_MAX = 200;
13
23
  async function post(provider, url, init, secrets = []) {
14
- const response = await fetch(url, { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
24
+ const response = await fetch(postable(url), { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
15
25
  if (!response.ok) {
16
26
  let text = "";
17
27
  try {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/honeybadger.ts"],"names":[],"mappings":";;;AAOO,IAAM,UAAA,GAAa,GAAA;AAYnB,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,MAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,eAAA;AAAA,EACT;AACF;AAGO,IAAM,cAAA,GAAiB,GAAA;AAW9B,eAAsB,KAAK,QAAA,EAAkB,GAAA,EAAa,IAAA,EAAyD,OAAA,GAAkC,EAAC,EAAsB;AAC1K,EAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,GAAA,EAAK,EAAE,MAAA,EAAQ,MAAA,EAAQ,SAAS,IAAA,CAAK,OAAA,EAAS,MAAM,IAAA,CAAK,IAAA,EAAM,UAAU,OAAA,EAAS,MAAA,EAAQ,YAAY,OAAA,CAAQ,UAAU,GAAG,CAAA;AACxJ,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,IAAI,IAAA,GAAO,EAAA;AACX,IAAA,IAAI;AACF,MAAA,IAAA,GAAO,MAAM,SAAS,IAAA,EAAK;AAAA,IAC7B,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,IAAI,MAAM,CAAA,EAAG,QAAQ,IAAI,MAAA,CAAO,GAAG,CAAC,CAAA,UAAA,EAAa,QAAA,CAAS,MAAM,CAAA,EAAG,IAAA,GAAO,KAAK,SAAA,CAAU,IAAA,EAAM,OAAO,CAAC,CAAA,CAAA,GAAK,EAAE,CAAA,CAAE,CAAA;AAAA,EACxH;AACA,EAAA,OAAO,QAAA;AACT;AAGO,SAAS,SAAA,CAAU,IAAA,EAAc,OAAA,GAAkC,EAAC,EAAW;AAC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AAW,CAAC,EAAE,MAAA,EAAQ,GAAA,EAAK,IAAA,EAAM,CAAA,UAAA,EAAa,KAAA,CAAM,GAAG,CAAA,CAAA,EAAI,MAAA,EAAQ,KAAA,CAAM,MAAM,CAAA;AAAA,UAC/E,aAAa,CAAA,UAAA,EAAa,KAAA,CAAM,GAAG,CAAA,CAAA,EAAI,MAAM,IAAI,CAAA,CAAA;AAAA,UACjD,IAAA,EAAM,CAAC,WAAA,EAAa,KAAA,CAAM,IAAI;AAAA,SAChC;AAAA,QACA,OAAA,EAAS;AAAA,UACP,SAAA,EAAW,WAAA;AAAA,UACX,QAAQ,KAAA,CAAM,GAAA;AAAA,UACd,GAAI,IAAA,GAAO,EAAE,GAAA,EAAK,IAAA,KAAS,EAAC;AAAA,UAC5B,OAAA,EAAS;AAAA,YACP,KAAK,KAAA,CAAM,GAAA;AAAA,YACX,MAAM,KAAA,CAAM,IAAA;AAAA,YACZ,GAAI,MAAM,MAAA,GAAS,EAAE,QAAQ,KAAA,CAAM,MAAA,KAAW,EAAC;AAAA,YAC/C,SAAS,KAAA,CAAM,OAAA;AAAA,YACf,GAAA,EAAK,WAAW,KAAK;AAAA;AACvB,SACF;AAAA,QACA,MAAA,EAAQ,EAAE,gBAAA,EAAkB,OAAA,CAAQ,eAAe,YAAA;AAAa,OAClE;AACA,MAAA,MAAM,IAAA,CAAK,eAAe,GAAA,EAAK;AAAA,QAC7B,SAAS,EAAE,cAAA,EAAgB,oBAAoB,MAAA,EAAQ,kBAAA,EAAoB,aAAa,MAAA,EAAO;AAAA,QAC/F,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,MAAM;AAAA,OAC7B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF","file":"honeybadger.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 type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/** How much of a provider's error body goes into the error message. */\nexport const ERROR_BODY_MAX = 200;\n\n/**\n * POSTs and throws on a non-2xx answer. The error names the provider and the\n * URL's origin, plus the start of the response body with every secret the\n * channel holds cut out, in case a provider echoes one back. Secrets are cut\n * from a prefix long enough to hold one that starts inside the first\n * ERROR_BODY_MAX characters, and only then is it cut to that length, so no\n * part of a secret survives at the edge. A redirect is refused rather than\n * followed: the credential headers would go with it to wherever it points.\n */\nexport async function post(provider: string, url: string, init: { headers: Record<string, string>; body: string }, secrets: (string | undefined)[] = []): Promise<Response> {\n const response = await fetch(url, { method: \"POST\", headers: init.headers, body: init.body, redirect: \"error\", signal: AbortSignal.timeout(TIMEOUT_MS) });\n if (!response.ok) {\n let text = \"\";\n try {\n text = await response.text();\n } catch {\n // The status is enough.\n }\n throw new Error(`${provider} ${origin(url)} answered ${response.status}${text ? `: ${errorBody(text, secrets)}` : \"\"}`);\n }\n return response;\n}\n\n/** The start of an error body, secrets cut out first, then cut to ERROR_BODY_MAX on a code point. */\nexport function errorBody(text: string, secrets: (string | undefined)[] = []): string {\n const kept = secrets.filter((s): s is string => typeof s === \"string\" && s.length >= 4);\n const longest = kept.reduce((n, s) => Math.max(n, s.length), 0);\n let head = cut(text, ERROR_BODY_MAX + longest);\n for (const secret of kept) head = head.split(secret).join(\"[redacted]\");\n return cut(head, ERROR_BODY_MAX);\n}\n\n/** A credential with the spaces and newlines a paste leaves around it taken off. Anything not a string is empty. */\nexport function trimmed(value: unknown): string {\n return typeof value === \"string\" ? value.trim() : \"\";\n}\n\n/** Base64 of UTF-8, without Buffer. */\nexport function base64(text: string): string {\n let binary = \"\";\n for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nexport function basicAuth(user: string, password: string): string {\n return `Basic ${base64(`${user}:${password}`)}`;\n}\n\nexport function hex(bytes: ArrayBuffer | Uint8Array): string {\n return Array.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function sha256Hex(text: string): Promise<string> {\n return hex(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text)));\n}\n\n/**\n * A stable 32 hex character id for one alert: the same job, type and time\n * always give the same id, so a provider that deduplicates on it drops a\n * resend of an alert it already took.\n */\nexport async function alertId(alert: Alert): Promise<string> {\n return (await sha256Hex(`${alert.job}\\n${alert.type}\\n${alert.at}`)).slice(0, 32);\n}\n\n/** The same id laid out as a UUID, for APIs that ask for one. */\nexport function asUuid(id: string): string {\n return `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20, 32)}`;\n}\n\n/** Cuts to at most `max` UTF-16 units without splitting a surrogate pair. */\nexport function cut(text: string, max: number): string {\n if (text.length <= max) return text;\n let end = max;\n const code = text.charCodeAt(end - 1);\n if (code >= 0xd800 && code <= 0xdbff) end -= 1;\n return text.slice(0, end);\n}\n\n/** The run fields worth attaching to a tracker event. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Honeybadger, as error notices (not Check-ins, a separate product).\n * API reference: https://docs.honeybadger.io/api/reporting-exceptions/\n * POST https://api.honeybadger.io/v1/notices with X-API-Key. Answers 201.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, post, runSummary, trimmed } from \"./shared.js\";\n\nexport interface HoneybadgerOptions {\n /** The project API key, from Project Settings. */\n apiKey: string;\n /** Defaults to \"production\". */\n environment?: string;\n /** Another API host, \"https://eu-api.honeybadger.io\" say. Defaults to https://api.honeybadger.io. */\n endpoint?: string;\n /** Also send recoveries. Defaults to false: Honeybadger has no levels, so a recovery would read as an error. */\n recovered?: boolean;\n link?: (alert: Alert) => string;\n}\n\nconst CLASS: Record<Alert[\"type\"], string> = {\n missed: \"CronWatch::Missed\",\n failed: \"CronWatch::Failed\",\n stuck: \"CronWatch::Stuck\",\n slow: \"CronWatch::Slow\",\n over_budget: \"CronWatch::OverBudget\",\n recovered: \"CronWatch::Recovered\",\n};\n\n/** Reports alerts to Honeybadger as notices, one error per job and alert type. */\nexport function honeybadger(options: HoneybadgerOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"honeybadger() needs an apiKey\");\n const url = `${(options.endpoint ?? \"https://api.honeybadger.io\").replace(/\\/+$/, \"\")}/v1/notices`;\n return {\n name: \"honeybadger\",\n async send(alert) {\n if (alert.type === \"recovered\" && !options.recovered) return;\n const link = options.link?.(alert);\n const notice = {\n notifier: { name: \"cronwatch\", url: \"https://cronwatch.dev\" },\n error: {\n class: CLASS[alert.type],\n message: cut(`${alert.title}\\n${alert.message}`, 8000),\n // No code ran here; one frame naming the job keeps the notice well formed.\n backtrace: [{ number: \"0\", file: `cronwatch/${alert.job}`, method: alert.type }],\n fingerprint: `cronwatch:${alert.job}:${alert.type}`,\n tags: [\"cronwatch\", alert.type],\n },\n request: {\n component: \"cronwatch\",\n action: alert.job,\n ...(link ? { url: link } : {}),\n context: {\n job: alert.job,\n type: alert.type,\n ...(alert.triage ? { triage: alert.triage } : {}),\n details: alert.details,\n run: runSummary(alert),\n },\n },\n server: { environment_name: options.environment ?? \"production\" },\n };\n await post(\"Honeybadger\", url, {\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"x-api-key\": apiKey },\n body: JSON.stringify(notice),\n }, [apiKey]);\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/alerts/shared.ts","../src/alerts/honeybadger.ts"],"names":[],"mappings":";;;AAOO,IAAM,UAAA,GAAa,GAAA;AAYnB,SAAS,OAAO,GAAA,EAAqB;AAC1C,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,MAAA;AAAA,EACtB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,eAAA;AAAA,EACT;AACF;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,EAAC,EAAsB;AAC1K,EAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,QAAA,CAAS,GAAG,CAAA,EAAG,EAAE,MAAA,EAAQ,MAAA,EAAQ,OAAA,EAAS,IAAA,CAAK,SAAS,IAAA,EAAM,IAAA,CAAK,MAAM,QAAA,EAAU,OAAA,EAAS,QAAQ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AAM,OAAA;AAAA,YACf,GAAA,EAAK,WAAW,KAAK;AAAA;AACvB,SACF;AAAA,QACA,MAAA,EAAQ,EAAE,gBAAA,EAAkB,OAAA,CAAQ,eAAe,YAAA;AAAa,OAClE;AACA,MAAA,MAAM,IAAA,CAAK,eAAe,GAAA,EAAK;AAAA,QAC7B,SAAS,EAAE,cAAA,EAAgB,oBAAoB,MAAA,EAAQ,kBAAA,EAAoB,aAAa,MAAA,EAAO;AAAA,QAC/F,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,MAAM;AAAA,OAC7B,EAAG,CAAC,MAAM,CAAC,CAAA;AAAA,IACb;AAAA,GACF;AACF","file":"honeybadger.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 type { Alert } from \"../types.js\";\n\nexport const TIMEOUT_MS = 10_000;\n\n/** Severity for trackers that have levels. Recovered is informational. */\nexport type Severity = \"error\" | \"warning\" | \"info\";\n\nexport function severity(type: Alert[\"type\"]): Severity {\n if (type === \"recovered\") return \"info\";\n if (type === \"slow\" || type === \"over_budget\") return \"warning\";\n return \"error\";\n}\n\n/** The scheme, host and port only. A URL's path or query can hold a credential. */\nexport function origin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/**\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. */\nexport function runSummary(alert: Alert): Record<string, unknown> | null {\n const run = alert.run;\n if (!run) return null;\n return { id: run.id, status: run.status, startedAt: new Date(run.startedAt).toISOString(), durationMs: run.durationMs, trigger: run.trigger };\n}\n\n/** Title, message, triage and link as one plain text block, the way every channel reads. */\nexport function plainText(alert: Alert, link: string | undefined): string {\n return [alert.title, \"\", alert.message, ...(alert.triage ? [\"\", `Triage: ${alert.triage}`] : []), ...(link ? [\"\", `Open: ${link}`] : [])].join(\"\\n\");\n}\n","/**\n * Honeybadger, as error notices (not Check-ins, a separate product).\n * API reference: https://docs.honeybadger.io/api/reporting-exceptions/\n * POST https://api.honeybadger.io/v1/notices with X-API-Key. Answers 201.\n */\nimport type { Alert, AlertChannel } from \"../types.js\";\nimport { cut, post, runSummary, trimmed } from \"./shared.js\";\n\nexport interface HoneybadgerOptions {\n /** The project API key, from Project Settings. */\n apiKey: string;\n /** Defaults to \"production\". */\n environment?: string;\n /** Another API host, \"https://eu-api.honeybadger.io\" say. Defaults to https://api.honeybadger.io. */\n endpoint?: string;\n /** Also send recoveries. Defaults to false: Honeybadger has no levels, so a recovery would read as an error. */\n recovered?: boolean;\n link?: (alert: Alert) => string;\n}\n\nconst CLASS: Record<Alert[\"type\"], string> = {\n missed: \"CronWatch::Missed\",\n failed: \"CronWatch::Failed\",\n stuck: \"CronWatch::Stuck\",\n slow: \"CronWatch::Slow\",\n over_budget: \"CronWatch::OverBudget\",\n recovered: \"CronWatch::Recovered\",\n};\n\n/** Reports alerts to Honeybadger as notices, one error per job and alert type. */\nexport function honeybadger(options: HoneybadgerOptions): AlertChannel {\n // A pasted credential often carries a stray space or newline, which a header would refuse or send.\n const apiKey = trimmed(options.apiKey);\n if (!apiKey) throw new Error(\"honeybadger() needs an apiKey\");\n const url = `${(options.endpoint ?? \"https://api.honeybadger.io\").replace(/\\/+$/, \"\")}/v1/notices`;\n return {\n name: \"honeybadger\",\n async send(alert) {\n if (alert.type === \"recovered\" && !options.recovered) return;\n const link = options.link?.(alert);\n const notice = {\n notifier: { name: \"cronwatch\", url: \"https://cronwatch.dev\" },\n error: {\n class: CLASS[alert.type],\n message: cut(`${alert.title}\\n${alert.message}`, 8000),\n // No code ran here; one frame naming the job keeps the notice well formed.\n backtrace: [{ number: \"0\", file: `cronwatch/${alert.job}`, method: alert.type }],\n fingerprint: `cronwatch:${alert.job}:${alert.type}`,\n tags: [\"cronwatch\", alert.type],\n },\n request: {\n component: \"cronwatch\",\n action: alert.job,\n ...(link ? { url: link } : {}),\n context: {\n job: alert.job,\n type: alert.type,\n ...(alert.triage ? { triage: alert.triage } : {}),\n details: alert.details,\n run: runSummary(alert),\n },\n },\n server: { environment_name: options.environment ?? \"production\" },\n };\n await post(\"Honeybadger\", url, {\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"x-api-key\": apiKey },\n body: JSON.stringify(notice),\n }, [apiKey]);\n },\n };\n}\n"]}
@@ -7,9 +7,19 @@ function origin(url) {
7
7
  return "(invalid URL)";
8
8
  }
9
9
  }
10
+ function postable(url) {
11
+ let protocol;
12
+ try {
13
+ protocol = new URL(url).protocol;
14
+ } catch {
15
+ throw new Error("only http and https URLs can be posted to, not this URL");
16
+ }
17
+ if (protocol !== "http:" && protocol !== "https:") throw new Error(`only http and https URLs can be posted to, not ${protocol}`);
18
+ return url;
19
+ }
10
20
  var ERROR_BODY_MAX = 200;
11
21
  async function post(provider, url, init, secrets = []) {
12
- const response = await fetch(url, { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
22
+ const response = await fetch(postable(url), { method: "POST", headers: init.headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
13
23
  if (!response.ok) {
14
24
  let text = "";
15
25
  try {