@narumitw/pi-notify 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -16
- package/docs/settings.md +319 -5
- package/package.json +15 -2
- package/src/destination-ui.ts +129 -0
- package/src/menu.ts +497 -60
- package/src/metadata.ts +25 -13
- package/src/notify.ts +3 -3
- package/src/provider.ts +82 -1
- package/src/providers/bark.ts +49 -0
- package/src/providers/discord.ts +66 -0
- package/src/providers/gotify.ts +121 -0
- package/src/providers/http.ts +125 -0
- package/src/providers/line.ts +91 -0
- package/src/providers/ntfy.ts +94 -0
- package/src/providers/pushover.ts +47 -0
- package/src/providers/slack.ts +132 -0
- package/src/providers/teams.ts +156 -0
- package/src/{telegram.ts → providers/telegram.ts} +40 -6
- package/src/providers/webhook.ts +48 -0
- package/src/providers.ts +24 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { type DeliveryResult, isObject, type NotificationProvider } from "../provider.js";
|
|
2
|
+
import { normalizeHttpUrl, postJson, truncateUtf8 } from "./http.js";
|
|
3
|
+
|
|
4
|
+
// Official contract: https://docs.ntfy.sh/publish/#publish-as-json
|
|
5
|
+
// Topics: https://docs.ntfy.sh/publish/#picking-a-topic
|
|
6
|
+
// Reserved names: https://github.com/binwiederhier/ntfy/blob/main/server/config.go (DefaultDisallowedTopics).
|
|
7
|
+
// These names are case-sensitive; self-hosted servers can forbid additional topics.
|
|
8
|
+
const RESERVED_TOPICS = new Set([
|
|
9
|
+
"docs",
|
|
10
|
+
"static",
|
|
11
|
+
"file",
|
|
12
|
+
"app",
|
|
13
|
+
"metrics",
|
|
14
|
+
"account",
|
|
15
|
+
"settings",
|
|
16
|
+
"signup",
|
|
17
|
+
"login",
|
|
18
|
+
"v1",
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
/** Anonymous or Bearer publishing only. Topic secrecy does not replace server access control. */
|
|
22
|
+
export function createNtfyProvider(fetcher: typeof fetch = fetch): NotificationProvider {
|
|
23
|
+
return {
|
|
24
|
+
id: "ntfy",
|
|
25
|
+
label: "ntfy",
|
|
26
|
+
validate(value) {
|
|
27
|
+
if (!isObject(value) || value.provider !== "ntfy") return undefined;
|
|
28
|
+
if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
|
|
29
|
+
if (!normalizeHttpUrl(value.serverUrl)) return undefined;
|
|
30
|
+
// Publishing targets the base itself; preserve its trailing slash for exact proxy mounts.
|
|
31
|
+
const serverUrl = new URL(String(value.serverUrl)).href;
|
|
32
|
+
if (serverUrl.length > 2048 || typeof value.topic !== "string" || !/^[-_A-Za-z0-9]{1,64}$/.test(value.topic))
|
|
33
|
+
return undefined;
|
|
34
|
+
if (RESERVED_TOPICS.has(value.topic)) return undefined;
|
|
35
|
+
// Local header-safety limit, not a claim that the server accepts any such token.
|
|
36
|
+
if (
|
|
37
|
+
value.accessToken !== undefined &&
|
|
38
|
+
(typeof value.accessToken !== "string" || !/^[\x21-\x7e]{1,512}$/.test(value.accessToken))
|
|
39
|
+
)
|
|
40
|
+
return undefined;
|
|
41
|
+
if (
|
|
42
|
+
value.priority !== undefined &&
|
|
43
|
+
(!Number.isInteger(value.priority) || Number(value.priority) < 1 || Number(value.priority) > 5)
|
|
44
|
+
)
|
|
45
|
+
return undefined;
|
|
46
|
+
return {
|
|
47
|
+
provider: "ntfy",
|
|
48
|
+
label: value.label,
|
|
49
|
+
serverUrl,
|
|
50
|
+
topic: value.topic,
|
|
51
|
+
accessToken: value.accessToken === undefined ? undefined : String(value.accessToken),
|
|
52
|
+
priority: value.priority === undefined ? undefined : Number(value.priority),
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
async send(destination, notification, signal): Promise<DeliveryResult> {
|
|
56
|
+
if (signal.aborted) return { state: "cancelled", code: "cancelled" };
|
|
57
|
+
const valid = this.validate(destination);
|
|
58
|
+
if (valid?.provider !== "ntfy") return { state: "failed", code: "invalid-destination" };
|
|
59
|
+
// https://docs.ntfy.sh/publish/#limitations: title 1 KiB, message 4096 UTF-8 bytes.
|
|
60
|
+
const payload = {
|
|
61
|
+
topic: valid.topic,
|
|
62
|
+
title: truncateUtf8(notification.title, 1024),
|
|
63
|
+
message: truncateUtf8(notification.body, 4096),
|
|
64
|
+
...(valid.priority === undefined ? {} : { priority: valid.priority }),
|
|
65
|
+
};
|
|
66
|
+
// The server's transformBodyJSON also caps the complete JSON envelope at 2 * message-size-limit.
|
|
67
|
+
// Escaped controls can exceed that limit even when the decoded strings fit their byte limits.
|
|
68
|
+
const excess = Buffer.byteLength(JSON.stringify(payload), "utf8") - 8192;
|
|
69
|
+
if (excess > 0)
|
|
70
|
+
payload.message = truncateUtf8(payload.message, Math.max(0, Buffer.byteLength(payload.message) - excess));
|
|
71
|
+
const result = await postJson(
|
|
72
|
+
valid.serverUrl,
|
|
73
|
+
payload,
|
|
74
|
+
signal,
|
|
75
|
+
fetcher,
|
|
76
|
+
valid.accessToken === undefined ? {} : { Authorization: `Bearer ${valid.accessToken}` },
|
|
77
|
+
);
|
|
78
|
+
if (result.state !== "response") return result;
|
|
79
|
+
// Publish returns a Message: https://docs.ntfy.sh/subscribe/api/#json-message-format
|
|
80
|
+
const body = result.body;
|
|
81
|
+
return result.status === 200 &&
|
|
82
|
+
isObject(body) &&
|
|
83
|
+
typeof body.id === "string" &&
|
|
84
|
+
body.id.length > 0 &&
|
|
85
|
+
Number.isSafeInteger(body.time) &&
|
|
86
|
+
Number(body.time) > 0 &&
|
|
87
|
+
body.event === "message" &&
|
|
88
|
+
body.topic === valid.topic &&
|
|
89
|
+
typeof body.message === "string"
|
|
90
|
+
? { state: "accepted" }
|
|
91
|
+
: { state: "failed", code: "response" };
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type DeliveryResult, isObject, type NotificationProvider } from "../provider.js";
|
|
2
|
+
import { clipText } from "../text.js";
|
|
3
|
+
import { postJson } from "./http.js";
|
|
4
|
+
|
|
5
|
+
// https://pushover.net/api: Messages API, response format, and limitations.
|
|
6
|
+
// Tokens and user/group keys are exactly 30 case-sensitive ASCII alphanumeric characters.
|
|
7
|
+
export function createPushoverProvider(fetcher: typeof fetch = fetch): NotificationProvider {
|
|
8
|
+
return {
|
|
9
|
+
id: "pushover",
|
|
10
|
+
label: "Pushover",
|
|
11
|
+
validate(value) {
|
|
12
|
+
if (!isObject(value) || value.provider !== "pushover") return undefined;
|
|
13
|
+
if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
|
|
14
|
+
if (
|
|
15
|
+
typeof value.appToken !== "string" ||
|
|
16
|
+
value.appToken.length !== 30 ||
|
|
17
|
+
!/^[A-Za-z0-9]{30}$/.test(value.appToken)
|
|
18
|
+
)
|
|
19
|
+
return undefined;
|
|
20
|
+
if (typeof value.userKey !== "string" || value.userKey.length !== 30 || !/^[A-Za-z0-9]{30}$/.test(value.userKey))
|
|
21
|
+
return undefined;
|
|
22
|
+
return { provider: "pushover", label: value.label, appToken: value.appToken, userKey: value.userKey };
|
|
23
|
+
},
|
|
24
|
+
async send(destination, notification, signal): Promise<DeliveryResult> {
|
|
25
|
+
if (signal.aborted) return { state: "cancelled", code: "cancelled" };
|
|
26
|
+
const valid = this.validate(destination);
|
|
27
|
+
if (valid?.provider !== "pushover") return { state: "failed", code: "invalid-destination" };
|
|
28
|
+
const result = await postJson(
|
|
29
|
+
"https://api.pushover.net/1/messages.json",
|
|
30
|
+
{
|
|
31
|
+
token: valid.appToken,
|
|
32
|
+
user: valid.userKey,
|
|
33
|
+
// UTF-16 budgets are conservative for the documented character limits.
|
|
34
|
+
title: clipText(notification.title, 250),
|
|
35
|
+
message: clipText(notification.body, 1024),
|
|
36
|
+
priority: 0,
|
|
37
|
+
},
|
|
38
|
+
signal,
|
|
39
|
+
fetcher,
|
|
40
|
+
);
|
|
41
|
+
if (result.state !== "response") return result;
|
|
42
|
+
if (result.status !== 200 || !isObject(result.body) || typeof result.body.status !== "number")
|
|
43
|
+
return { state: "failed", code: "response" };
|
|
44
|
+
return result.body.status === 1 ? { state: "accepted" } : { state: "failed", code: "api" };
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -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 === "&" ? "&" : character === "<" ? "<" : character === ">" ? ">" : 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
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
2
|
+
import { type DeliveryResult, isObject, type NotificationProvider } from "../provider.js";
|
|
3
|
+
import { postJson } from "./http.js";
|
|
4
|
+
|
|
5
|
+
// Local support policy, not a complete Microsoft URL grammar. Reviewed 2026-10-18:
|
|
6
|
+
// https://learn.microsoft.com/en-us/power-automate/triggers-troubleshoot
|
|
7
|
+
// documents migration from logic.azure.com and the optional /direct/cu/20 route.
|
|
8
|
+
// https://learn.microsoft.com/en-us/connectors/teams/#microsoft-teams-webhook
|
|
9
|
+
// documents Anyone authentication (no Authorization header) and the card envelope.
|
|
10
|
+
// https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-http-endpoint
|
|
11
|
+
// documents signed Request URLs; this is corroboration, not a Teams URL/response contract.
|
|
12
|
+
// Public current-format example (corroboration only):
|
|
13
|
+
// https://dev.classmethod.jp/en/articles/aws-step-functions-teams-workflows-new-webhook-url/
|
|
14
|
+
// Support only literal lowercase commercial DNS hosts with one or more valid prefix
|
|
15
|
+
// labels before .environment.api.powerplatform.com; labels <=63, entire host <=253.
|
|
16
|
+
// Require HTTPS, no userinfo, and no port except an explicit generated :443.
|
|
17
|
+
// Paths are exactly /powerautomate/automations/direct/[cu/<route>/]workflows/<id>
|
|
18
|
+
// /triggers/manual/paths/invoke. Route/id are opaque ASCII letters, digits, _ or -,
|
|
19
|
+
// 1..256 characters each: a local bound, NOT an inferred fixed-length service ID.
|
|
20
|
+
// Reject all encoded hosts/paths, dot segments, fragments, whitespace, controls and
|
|
21
|
+
// backslashes before a URL parser could normalize them. Total URL cap: 8,192 chars.
|
|
22
|
+
// Query keys must be literal api-version, sp, sv, sig, exactly once, in any order.
|
|
23
|
+
// api-version=1 and sv=1.0 are literal; decoded sp is /triggers/manual/run.
|
|
24
|
+
// Decoded sig is nonempty opaque base64/base64url syntax (up to two trailing =).
|
|
25
|
+
// Percent escapes must be valid UTF-8. In particular, + is NOT form-decoded to space.
|
|
26
|
+
// Preserve the COMPLETE raw signed URL, including port, escape case and query order.
|
|
27
|
+
const MAX_URL_LENGTH = 8192;
|
|
28
|
+
const HOST_SUFFIX = ".environment.api.powerplatform.com";
|
|
29
|
+
const DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
|
|
30
|
+
const WORKFLOW_PATH =
|
|
31
|
+
/^\/powerautomate\/automations\/direct\/(?:cu\/[A-Za-z0-9_-]{1,256}\/)?workflows\/[A-Za-z0-9_-]{1,256}\/triggers\/manual\/paths\/invoke$/u;
|
|
32
|
+
|
|
33
|
+
function workflowUrl(value: unknown): string | undefined {
|
|
34
|
+
if (typeof value !== "string" || value.length > MAX_URL_LENGTH || /[\s\\\p{Cc}]/u.test(value)) return undefined;
|
|
35
|
+
const parts = /^https:\/\/([^/?#]+)(\/[^?#]+)\?([^#]+)$/u.exec(value);
|
|
36
|
+
if (!parts) return undefined;
|
|
37
|
+
const [, authority = "", path = "", query = ""] = parts;
|
|
38
|
+
const hostname = authority.endsWith(":443") ? authority.slice(0, -4) : authority;
|
|
39
|
+
if (
|
|
40
|
+
hostname.length > 253 ||
|
|
41
|
+
!hostname.endsWith(HOST_SUFFIX) ||
|
|
42
|
+
hostname.length <= HOST_SUFFIX.length ||
|
|
43
|
+
!hostname.split(".").every((label) => DNS_LABEL.test(label)) ||
|
|
44
|
+
!WORKFLOW_PATH.test(path)
|
|
45
|
+
)
|
|
46
|
+
return undefined;
|
|
47
|
+
const values = new Map<string, string>();
|
|
48
|
+
try {
|
|
49
|
+
for (const pair of query.split("&")) {
|
|
50
|
+
const separator = pair.indexOf("=");
|
|
51
|
+
if (separator < 0) return undefined;
|
|
52
|
+
const key = pair.slice(0, separator);
|
|
53
|
+
const raw = pair.slice(separator + 1);
|
|
54
|
+
if (!["api-version", "sp", "sv", "sig"].includes(key) || values.has(key)) return undefined;
|
|
55
|
+
const decoded = decodeURIComponent(raw);
|
|
56
|
+
// Also reject encoded terminal whitespace: JavaScript's $ can precede a final newline.
|
|
57
|
+
if (/[\s\\\p{Cc}]/u.test(decoded)) return undefined;
|
|
58
|
+
if ((key === "api-version" && raw !== "1") || (key === "sv" && raw !== "1.0")) return undefined;
|
|
59
|
+
values.set(key, decoded);
|
|
60
|
+
}
|
|
61
|
+
} catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
if (
|
|
65
|
+
values.size !== 4 ||
|
|
66
|
+
values.get("sp") !== "/triggers/manual/run" ||
|
|
67
|
+
!/^[A-Za-z0-9_+/-]+={0,2}$/u.test(values.get("sig") ?? "")
|
|
68
|
+
)
|
|
69
|
+
return undefined;
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function card(text: string) {
|
|
74
|
+
return {
|
|
75
|
+
type: "message",
|
|
76
|
+
attachments: [
|
|
77
|
+
{
|
|
78
|
+
contentType: "application/vnd.microsoft.card.adaptive",
|
|
79
|
+
contentUrl: null,
|
|
80
|
+
content: {
|
|
81
|
+
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
|
|
82
|
+
type: "AdaptiveCard",
|
|
83
|
+
version: "1.2",
|
|
84
|
+
// TextRun has no Markdown support. No actions, images or mention entities.
|
|
85
|
+
// https://learn.microsoft.com/en-us/adaptive-cards/schema-explorer/text-run
|
|
86
|
+
// Clients can still auto-link text; this does not promise link suppression.
|
|
87
|
+
body: [{ type: "RichTextBlock", inlines: [{ type: "TextRun", text }] }],
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// A local encoded-JSON budget, NOT proof of Teams' downstream rendered-card size.
|
|
95
|
+
// https://learn.microsoft.com/en-us/connectors/teams/#known-issues-and-limitations
|
|
96
|
+
// The connector's approximate 28 KB limit includes rendered elements.
|
|
97
|
+
const MAX_PAYLOAD_BYTES = 24_000;
|
|
98
|
+
const TEXT_BUDGET = MAX_PAYLOAD_BYTES - Buffer.byteLength(JSON.stringify(card("")), "utf8");
|
|
99
|
+
|
|
100
|
+
function boundedText(title: string, body: string): string {
|
|
101
|
+
const text = `${title}\n${body}`.split("\n").map(sanitizeTerminalText).join("\n");
|
|
102
|
+
const points: string[] = [];
|
|
103
|
+
const costs: number[] = [];
|
|
104
|
+
let bytes = 0;
|
|
105
|
+
for (const point of text) {
|
|
106
|
+
// Count JSON escapes as well as UTF-8, using only constant-sized serializations.
|
|
107
|
+
const cost = Buffer.byteLength(JSON.stringify(point), "utf8") - 2;
|
|
108
|
+
if (bytes + cost > TEXT_BUDGET) {
|
|
109
|
+
while (bytes + 3 > TEXT_BUDGET) {
|
|
110
|
+
bytes -= costs.pop() ?? 0;
|
|
111
|
+
points.pop();
|
|
112
|
+
}
|
|
113
|
+
return `${points.join("")}…`;
|
|
114
|
+
}
|
|
115
|
+
bytes += cost;
|
|
116
|
+
points.push(point);
|
|
117
|
+
costs.push(cost);
|
|
118
|
+
}
|
|
119
|
+
return points.join("");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One workflow request. Local acceptance is HTTP 202, never downstream-post proof. */
|
|
123
|
+
export function createTeamsProvider(fetcher: typeof fetch = fetch): NotificationProvider {
|
|
124
|
+
return {
|
|
125
|
+
id: "teams",
|
|
126
|
+
label: "Microsoft Teams",
|
|
127
|
+
validate(value) {
|
|
128
|
+
if (!isObject(value) || value.provider !== "teams") return undefined;
|
|
129
|
+
if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
|
|
130
|
+
const webhookUrl = workflowUrl(value.webhookUrl);
|
|
131
|
+
return webhookUrl ? { provider: "teams", label: value.label, webhookUrl } : undefined;
|
|
132
|
+
},
|
|
133
|
+
async send(destination, notification, signal): Promise<DeliveryResult> {
|
|
134
|
+
if (signal.aborted) return { state: "cancelled", code: "cancelled" };
|
|
135
|
+
const valid = this.validate(destination);
|
|
136
|
+
if (valid?.provider !== "teams") return { state: "failed", code: "invalid-destination" };
|
|
137
|
+
const result = await postJson(
|
|
138
|
+
valid.webhookUrl,
|
|
139
|
+
card(boundedText(notification.title, notification.body)),
|
|
140
|
+
signal,
|
|
141
|
+
fetcher,
|
|
142
|
+
);
|
|
143
|
+
if (result.state !== "response") return result;
|
|
144
|
+
// Explicit local status-only policy after the FULL bounded response read:
|
|
145
|
+
// https://www.rfc-editor.org/rfc/rfc9110.html#section-15.3.3
|
|
146
|
+
// 202 means accepted for processing, not completed. The Request documentation
|
|
147
|
+
// above corroborates default 202 without a Response action, but does not define
|
|
148
|
+
// Teams responses. A public workflow example also reports 202 despite a later
|
|
149
|
+
// workflow failure (corroboration only, NOT a normative Teams response shape):
|
|
150
|
+
// https://simonscholz.dev/tutorials/microsoft-teams-messages-webhook-workflow/
|
|
151
|
+
// Ignore bounded empty/text/JSON bodies and undocumented fields.
|
|
152
|
+
// Live Teams interoperability and downstream receipt remain unverified.
|
|
153
|
+
return result.status === 202 ? { state: "accepted" } : { state: "failed", code: "response" };
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
@@ -1,10 +1,45 @@
|
|
|
1
|
-
import { type DeliveryResult, isObject, type NotificationProvider } from "
|
|
2
|
-
import { clipText } from "
|
|
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
|
-
|
|
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
|
-
|
|
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
|
+
}
|
package/src/providers.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
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 { createLineProvider } from "./providers/line.js";
|
|
6
|
+
import { createNtfyProvider } from "./providers/ntfy.js";
|
|
7
|
+
import { createPushoverProvider } from "./providers/pushover.js";
|
|
8
|
+
import { createSlackProvider } from "./providers/slack.js";
|
|
9
|
+
import { createTeamsProvider } from "./providers/teams.js";
|
|
10
|
+
import { createTelegramProvider } from "./providers/telegram.js";
|
|
11
|
+
import { createWebhookProvider } from "./providers/webhook.js";
|
|
12
|
+
|
|
13
|
+
export const providers: Providers = new Map([
|
|
14
|
+
["telegram", createTelegramProvider()],
|
|
15
|
+
["gotify", createGotifyProvider()],
|
|
16
|
+
["slack", createSlackProvider()],
|
|
17
|
+
["ntfy", createNtfyProvider()],
|
|
18
|
+
["pushover", createPushoverProvider()],
|
|
19
|
+
["discord", createDiscordProvider()],
|
|
20
|
+
["bark", createBarkProvider()],
|
|
21
|
+
["webhook", createWebhookProvider()],
|
|
22
|
+
["line", createLineProvider()],
|
|
23
|
+
["teams", createTeamsProvider()],
|
|
24
|
+
]);
|