@narumitw/pi-notify 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,132 @@
1
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
2
+ import { type DeliveryResult, isObject, type Notification, type NotificationProvider } from "../provider.js";
3
+
4
+ const TIMEOUT_MS = 10_000;
5
+ const MAX_RESPONSE_BYTES = 65_536;
6
+
7
+ /** Slack decodes these entities even in plain_text. Bound encoded length without cutting an entity. */
8
+ function slackText(notification: Notification): string {
9
+ const raw = `${notification.title}\n${notification.body}`.split("\n").map(sanitizeTerminalText).join("\n");
10
+ let text = "";
11
+ let beforeLast = 0;
12
+ for (const character of raw) {
13
+ const escaped = character === "&" ? "&amp;" : character === "<" ? "&lt;" : character === ">" ? "&gt;" : character;
14
+ if (text.length + escaped.length > 3000) return `${text.length === 3000 ? text.slice(0, beforeLast) : text}…`;
15
+ beforeLast = text.length;
16
+ text += escaped;
17
+ }
18
+ return text.trim() ? text : "Pi notification";
19
+ }
20
+
21
+ /** Match the commercial webhook literal, not a URL parser's normalized interpretation.
22
+ * https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/
23
+ */
24
+ export function validateSlackWebhookUrl(value: unknown): value is string {
25
+ return (
26
+ typeof value === "string" &&
27
+ value.length <= 2048 &&
28
+ !/\s/.test(value) &&
29
+ /^https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+$/.test(value)
30
+ );
31
+ }
32
+
33
+ /** Fixed channel, no redirects or retries; the entire URL is a credential. */
34
+ export function createSlackProvider(fetcher: typeof fetch = fetch): NotificationProvider {
35
+ return {
36
+ id: "slack",
37
+ label: "Slack",
38
+ validate(value) {
39
+ if (!isObject(value) || value.provider !== "slack") return undefined;
40
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
41
+ if (!validateSlackWebhookUrl(value.webhookUrl)) return undefined;
42
+ return { provider: "slack", label: value.label, webhookUrl: value.webhookUrl };
43
+ },
44
+ async send(destination, notification, signal): Promise<DeliveryResult> {
45
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
46
+ const valid = this.validate(destination);
47
+ if (valid?.provider !== "slack") return { state: "failed", code: "invalid-destination" };
48
+ const timeout = new AbortController();
49
+ const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);
50
+ const combined = AbortSignal.any([signal, timeout.signal]);
51
+ try {
52
+ // Plain text disables Slack formatting. Keep untrusted metadata out of the
53
+ // fallback, which Slack also uses for notifications and screen readers.
54
+ // https://docs.slack.dev/messaging/formatting-message-text/#disabling-formatting
55
+ // Escape Slack control characters exactly once, including existing entity-like text.
56
+ // https://docs.slack.dev/messaging/formatting-message-text/#escaping
57
+ // Section text is limited to 3,000 characters; UTF-16 length is conservative.
58
+ // https://docs.slack.dev/reference/block-kit/blocks/section-block/
59
+ const response = await fetcher(valid.webhookUrl, {
60
+ method: "POST",
61
+ redirect: "error",
62
+ signal: combined,
63
+ headers: { "content-type": "application/json" },
64
+ body: JSON.stringify({
65
+ text: "Pi notification. Open Pi to review.",
66
+ mrkdwn: false,
67
+ parse: "none",
68
+ unfurl_links: false,
69
+ unfurl_media: false,
70
+ blocks: [
71
+ {
72
+ type: "section",
73
+ text: { type: "plain_text", text: slackText(notification), emoji: false },
74
+ },
75
+ ],
76
+ }),
77
+ });
78
+ if (combined.aborted || response.status !== 200) {
79
+ // Do not await an untrusted stream's potentially stalled cancellation.
80
+ void response.body?.cancel().catch(() => {});
81
+ combined.throwIfAborted();
82
+ const retry = response.headers.get("retry-after");
83
+ return {
84
+ state: "failed",
85
+ code: response.status === 429 ? "rate-limit" : "http",
86
+ ...(response.status === 429 &&
87
+ retry &&
88
+ /^\d+$/.test(retry) &&
89
+ Number.isSafeInteger(Number(retry)) &&
90
+ Number(retry) > 0
91
+ ? { retryAfterSeconds: Number(retry) }
92
+ : {}),
93
+ };
94
+ }
95
+ const reader = response.body?.getReader();
96
+ if (!reader) return { state: "failed", code: "response" };
97
+ // Also interrupt injected streams that do not observe the fetch signal.
98
+ const cancel = () => {
99
+ void reader.cancel().catch(() => {});
100
+ };
101
+ combined.addEventListener("abort", cancel, { once: true });
102
+ let length = 0;
103
+ const chunks: Uint8Array[] = [];
104
+ try {
105
+ while (true) {
106
+ combined.throwIfAborted();
107
+ const part = await reader.read();
108
+ combined.throwIfAborted();
109
+ if (part.done) break;
110
+ length += part.value.byteLength;
111
+ if (length > MAX_RESPONSE_BYTES) break;
112
+ if (part.value.byteLength) chunks.push(part.value);
113
+ }
114
+ } finally {
115
+ combined.removeEventListener("abort", cancel);
116
+ cancel();
117
+ reader.releaseLock();
118
+ }
119
+ combined.throwIfAborted();
120
+ // Only the documented HTTP 200 and exact plain-text `ok` is acceptance.
121
+ return length <= MAX_RESPONSE_BYTES && Buffer.concat(chunks).equals(Buffer.from("ok"))
122
+ ? { state: "accepted" }
123
+ : { state: "failed", code: "response" };
124
+ } catch {
125
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
126
+ return { state: "failed", code: timeout.signal.aborted ? "timeout" : "network" };
127
+ } finally {
128
+ clearTimeout(timer);
129
+ }
130
+ },
131
+ };
132
+ }
@@ -1,10 +1,45 @@
1
- import { type DeliveryResult, isObject, type NotificationProvider } from "./provider.js";
2
- import { clipText } from "./text.js";
1
+ import { type DeliveryResult, isObject, type Notification, type NotificationProvider } from "../provider.js";
2
+ import { clipText } from "../text.js";
3
3
 
4
4
  const TIMEOUT_MS = 10_000;
5
5
  const MAX_RESPONSE_BYTES = 65_536;
6
6
 
7
- /** No user-configurable origin, redirects, paid broadcasts, formatting, or retries. */
7
+ function codePointBoundary(text: string, offset: number): boolean {
8
+ const before = text.charCodeAt(offset - 1);
9
+ const after = text.charCodeAt(offset);
10
+ return !(before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff);
11
+ }
12
+
13
+ function telegramMessage(notification: Notification) {
14
+ const source = `${notification.title}\n${notification.body}`;
15
+ const text = clipText(source, 4096);
16
+ // Telegram entities use UTF-16 units. Do not style the clipping ellipsis.
17
+ // https://core.telegram.org/bots/api#messageentity
18
+ const contentEnd = text.length - (text === source ? 0 : 1);
19
+ const ranges = [
20
+ { style: "bold" as const, offset: 0, length: notification.title.length },
21
+ ...(notification.bodyEmphasis ?? []).flatMap((range) =>
22
+ Number.isSafeInteger(range.offset) &&
23
+ Number.isSafeInteger(range.length) &&
24
+ range.offset >= 0 &&
25
+ range.length > 0 &&
26
+ range.offset + range.length <= notification.body.length
27
+ ? [{ ...range, offset: notification.title.length + 1 + range.offset }]
28
+ : [],
29
+ ),
30
+ ];
31
+ const entities = ranges.flatMap(({ style, offset, length }) => {
32
+ // Trim only the retained entity, not the text or later offsets.
33
+ // https://core.telegram.org/api/entities#entity-length
34
+ const retained = source.slice(offset, Math.min(offset + length, contentEnd)).trimEnd();
35
+ const end = offset + retained.length;
36
+ if (end <= offset || !codePointBoundary(source, offset) || !codePointBoundary(source, end)) return [];
37
+ return [{ type: style === "bold" ? "bold" : "code", offset, length: end - offset }];
38
+ });
39
+ return { text, entities };
40
+ }
41
+
42
+ /** No user-configurable origin, redirects, paid broadcasts, parse mode, or retries. */
8
43
  export function createTelegramProvider(fetcher: typeof fetch = fetch): NotificationProvider {
9
44
  return {
10
45
  id: "telegram",
@@ -30,6 +65,7 @@ export function createTelegramProvider(fetcher: typeof fetch = fetch): Notificat
30
65
  },
31
66
  async send(destination, notification, signal): Promise<DeliveryResult> {
32
67
  if (signal.aborted) return { state: "cancelled", code: "cancelled" };
68
+ if (destination.provider !== "telegram") return { state: "failed", code: "invalid-destination" };
33
69
  const timeout = new AbortController();
34
70
  const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);
35
71
  const combined = AbortSignal.any([signal, timeout.signal]);
@@ -42,7 +78,7 @@ export function createTelegramProvider(fetcher: typeof fetch = fetch): Notificat
42
78
  body: JSON.stringify({
43
79
  chat_id: destination.chatId,
44
80
  ...(destination.messageThreadId === undefined ? {} : { message_thread_id: destination.messageThreadId }),
45
- text: clipText(`${notification.title}\n${notification.body}`, 4096),
81
+ ...telegramMessage(notification),
46
82
  link_preview_options: { is_disabled: true },
47
83
  }),
48
84
  });
@@ -90,5 +126,3 @@ export function createTelegramProvider(fetcher: typeof fetch = fetch): Notificat
90
126
  },
91
127
  };
92
128
  }
93
-
94
- export const providers = new Map([["telegram", createTelegramProvider()]]);
@@ -0,0 +1,48 @@
1
+ import { type DeliveryResult, isObject, type NotificationProvider } from "../provider.js";
2
+ import { normalizeHttpUrl, postJson } from "./http.js";
3
+
4
+ /** A fixed metadata contract; HTTP 2xx means endpoint acceptance, not downstream delivery. */
5
+ export function createWebhookProvider(fetcher: typeof fetch = fetch): NotificationProvider {
6
+ return {
7
+ id: "webhook",
8
+ label: "Generic webhook",
9
+ validate(value) {
10
+ if (!isObject(value) || value.provider !== "webhook") return undefined;
11
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
12
+ if (!normalizeHttpUrl(value.webhookUrl)) return undefined;
13
+ // This is an exact endpoint, not a server base: trailing slashes can select a different route.
14
+ const webhookUrl = new URL(String(value.webhookUrl)).href;
15
+ if (webhookUrl.length > 2048) return undefined;
16
+ // Local printable-ASCII header-safety limit (no spaces), not an endpoint token-format claim.
17
+ if (
18
+ value.bearerToken !== undefined &&
19
+ (typeof value.bearerToken !== "string" || !/^[\x21-\x7e]{1,512}$/.test(value.bearerToken))
20
+ )
21
+ return undefined;
22
+ return {
23
+ provider: "webhook",
24
+ label: value.label,
25
+ webhookUrl,
26
+ bearerToken: value.bearerToken === undefined ? undefined : String(value.bearerToken),
27
+ };
28
+ },
29
+ async send(destination, notification, signal): Promise<DeliveryResult> {
30
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
31
+ const valid = this.validate(destination);
32
+ if (valid?.provider !== "webhook") return { state: "failed", code: "invalid-destination" };
33
+ const result = await postJson(
34
+ valid.webhookUrl,
35
+ {
36
+ id: notification.id,
37
+ title: notification.title,
38
+ body: notification.body,
39
+ settledAt: notification.settledAt,
40
+ },
41
+ signal,
42
+ fetcher,
43
+ valid.bearerToken === undefined ? {} : { Authorization: `Bearer ${valid.bearerToken}` },
44
+ );
45
+ return result.state === "response" ? { state: "accepted" } : result;
46
+ },
47
+ };
48
+ }
@@ -0,0 +1,20 @@
1
+ import type { Providers } from "./provider.js";
2
+ import { createBarkProvider } from "./providers/bark.js";
3
+ import { createDiscordProvider } from "./providers/discord.js";
4
+ import { createGotifyProvider } from "./providers/gotify.js";
5
+ import { createNtfyProvider } from "./providers/ntfy.js";
6
+ import { createPushoverProvider } from "./providers/pushover.js";
7
+ import { createSlackProvider } from "./providers/slack.js";
8
+ import { createTelegramProvider } from "./providers/telegram.js";
9
+ import { createWebhookProvider } from "./providers/webhook.js";
10
+
11
+ export const providers: Providers = new Map([
12
+ ["telegram", createTelegramProvider()],
13
+ ["gotify", createGotifyProvider()],
14
+ ["slack", createSlackProvider()],
15
+ ["ntfy", createNtfyProvider()],
16
+ ["pushover", createPushoverProvider()],
17
+ ["discord", createDiscordProvider()],
18
+ ["bark", createBarkProvider()],
19
+ ["webhook", createWebhookProvider()],
20
+ ]);