@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.
- package/README.md +36 -16
- package/docs/settings.md +215 -5
- package/package.json +10 -2
- package/src/destination-ui.ts +107 -0
- package/src/menu.ts +418 -60
- package/src/metadata.ts +25 -13
- package/src/notify.ts +3 -3
- package/src/provider.ts +67 -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/ntfy.ts +94 -0
- package/src/providers/pushover.ts +47 -0
- package/src/providers/slack.ts +132 -0
- package/src/{telegram.ts → providers/telegram.ts} +40 -6
- package/src/providers/webhook.ts +48 -0
- package/src/providers.ts +20 -0
package/src/metadata.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { execFile } from "node:child_process";
|
|
|
2
2
|
import { homedir, hostname } from "node:os";
|
|
3
3
|
import { basename, dirname, isAbsolute, sep } from "node:path";
|
|
4
4
|
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
5
|
-
import type { Notification } from "./provider.js";
|
|
5
|
+
import type { BodyEmphasis, Notification } from "./provider.js";
|
|
6
6
|
import { clipText } from "./text.js";
|
|
7
7
|
|
|
8
8
|
export interface Metadata {
|
|
@@ -39,11 +39,23 @@ export async function notificationMetadata(data: Metadata, signal: AbortSignal):
|
|
|
39
39
|
signal.throwIfAborted();
|
|
40
40
|
const detached = branch === "HEAD" ? await git(data.cwd, ["--short", "HEAD"], signal) : undefined;
|
|
41
41
|
signal.throwIfAborted();
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
42
|
+
let body = "";
|
|
43
|
+
const bodyEmphasis: BodyEmphasis[] = [];
|
|
44
|
+
const line = (label: string, value: string, style?: BodyEmphasis["style"], prefix = "", suffix = "") => {
|
|
45
|
+
if (body) body += "\n";
|
|
46
|
+
body += `${label}: ${prefix}`;
|
|
47
|
+
if (style && value.length) bodyEmphasis.push({ style, offset: body.length, length: value.length });
|
|
48
|
+
body += value + suffix;
|
|
49
|
+
};
|
|
50
|
+
line("Computer", safeText(hostname()));
|
|
51
|
+
line(
|
|
52
|
+
"Session",
|
|
53
|
+
safeText(data.sessionId),
|
|
54
|
+
"monospace",
|
|
55
|
+
`${data.sessionName ? `${safeText(data.sessionName)} ` : ""}(`,
|
|
56
|
+
")",
|
|
57
|
+
);
|
|
58
|
+
line("Workspace", displayPath(data.cwd), "monospace");
|
|
47
59
|
if (root) {
|
|
48
60
|
// Sanitize before splitting paths. Common Git directory names identify linked worktrees.
|
|
49
61
|
const cleanRoot = safeText(root);
|
|
@@ -53,17 +65,17 @@ export async function notificationMetadata(data: Metadata, signal: AbortSignal):
|
|
|
53
65
|
commonDirectory && basename(commonDirectory) === ".git"
|
|
54
66
|
? basename(dirname(commonDirectory))
|
|
55
67
|
: basename(cleanRoot);
|
|
56
|
-
|
|
57
|
-
|
|
68
|
+
line("Repository", repository, "bold");
|
|
69
|
+
line("Worktree", displayPath(root), "monospace");
|
|
70
|
+
if (branch) line("Branch", safeText(branch === "HEAD" ? `detached ${detached ?? "HEAD"}` : branch), "monospace");
|
|
58
71
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
`Stopped: ${new Date(data.settledAt).toISOString()}`,
|
|
62
|
-
);
|
|
72
|
+
line("Elapsed", `${Math.max(0, Math.floor((data.settledAt - data.startedAt) / 1000))}s`);
|
|
73
|
+
line("Stopped", new Date(data.settledAt).toISOString());
|
|
63
74
|
return {
|
|
64
75
|
id: data.id,
|
|
65
76
|
title: data.error ? "Pi stopped with an error" : "Pi is ready for review",
|
|
66
|
-
body
|
|
77
|
+
body,
|
|
78
|
+
bodyEmphasis,
|
|
67
79
|
settledAt: data.settledAt,
|
|
68
80
|
};
|
|
69
81
|
}
|
package/src/notify.ts
CHANGED
|
@@ -7,8 +7,8 @@ import {
|
|
|
7
7
|
} from "@earendil-works/pi-coding-agent";
|
|
8
8
|
import { Coordinator } from "./coordinator.js";
|
|
9
9
|
import { displayPath } from "./metadata.js";
|
|
10
|
+
import { providers } from "./providers.js";
|
|
10
11
|
import { defaults, SettingsStore } from "./settings.js";
|
|
11
|
-
import { providers } from "./telegram.js";
|
|
12
12
|
|
|
13
13
|
interface Owner {
|
|
14
14
|
controller: AbortController;
|
|
@@ -43,7 +43,7 @@ export default function notify(pi: ExtensionAPI): void {
|
|
|
43
43
|
store,
|
|
44
44
|
coordinator: new Coordinator(defaults(), providers, ctx.mode === "tui", undefined, () => {
|
|
45
45
|
if (owners.get(manager) === owner && !controller.signal.aborted && hasUI)
|
|
46
|
-
ui.notify("
|
|
46
|
+
ui.notify("Notification failed. Open /notify → Status for a safe error code.", "warning");
|
|
47
47
|
}),
|
|
48
48
|
};
|
|
49
49
|
owners.set(manager, owner);
|
|
@@ -85,7 +85,7 @@ export default function notify(pi: ExtensionAPI): void {
|
|
|
85
85
|
await stop(owner);
|
|
86
86
|
});
|
|
87
87
|
pi.registerCommand("notify", {
|
|
88
|
-
description: "Configure
|
|
88
|
+
description: "Configure notification destinations and inactivity reminders",
|
|
89
89
|
handler: async (args, ctx) => {
|
|
90
90
|
if (args.trim()) throw new Error("Usage: /notify (no arguments).");
|
|
91
91
|
const owner = current(ctx);
|
package/src/provider.ts
CHANGED
|
@@ -6,12 +6,78 @@ export interface TelegramDestination {
|
|
|
6
6
|
messageThreadId?: number;
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
-
export
|
|
9
|
+
export interface GotifyDestination {
|
|
10
|
+
provider: "gotify";
|
|
11
|
+
label: string;
|
|
12
|
+
serverUrl: string;
|
|
13
|
+
appToken: string;
|
|
14
|
+
priority?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface NtfyDestination {
|
|
18
|
+
provider: "ntfy";
|
|
19
|
+
label: string;
|
|
20
|
+
serverUrl: string;
|
|
21
|
+
topic: string;
|
|
22
|
+
accessToken?: string;
|
|
23
|
+
priority?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SlackDestination {
|
|
27
|
+
provider: "slack";
|
|
28
|
+
label: string;
|
|
29
|
+
webhookUrl: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface PushoverDestination {
|
|
33
|
+
provider: "pushover";
|
|
34
|
+
label: string;
|
|
35
|
+
appToken: string;
|
|
36
|
+
userKey: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface DiscordDestination {
|
|
40
|
+
provider: "discord";
|
|
41
|
+
label: string;
|
|
42
|
+
webhookUrl: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface BarkDestination {
|
|
46
|
+
provider: "bark";
|
|
47
|
+
label: string;
|
|
48
|
+
serverUrl: string;
|
|
49
|
+
deviceKey: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface WebhookDestination {
|
|
53
|
+
provider: "webhook";
|
|
54
|
+
label: string;
|
|
55
|
+
webhookUrl: string;
|
|
56
|
+
bearerToken?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type Destination =
|
|
60
|
+
| TelegramDestination
|
|
61
|
+
| GotifyDestination
|
|
62
|
+
| SlackDestination
|
|
63
|
+
| NtfyDestination
|
|
64
|
+
| PushoverDestination
|
|
65
|
+
| DiscordDestination
|
|
66
|
+
| BarkDestination
|
|
67
|
+
| WebhookDestination;
|
|
68
|
+
|
|
69
|
+
export interface BodyEmphasis {
|
|
70
|
+
style: "bold" | "monospace";
|
|
71
|
+
/** Offset and length in UTF-16 code units of the sanitized body. */
|
|
72
|
+
offset: number;
|
|
73
|
+
length: number;
|
|
74
|
+
}
|
|
10
75
|
|
|
11
76
|
export interface Notification {
|
|
12
77
|
id: string;
|
|
13
78
|
title: string;
|
|
14
79
|
body: string;
|
|
80
|
+
bodyEmphasis?: BodyEmphasis[];
|
|
15
81
|
settledAt: number;
|
|
16
82
|
}
|
|
17
83
|
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type DeliveryResult, isObject, type NotificationProvider } from "../provider.js";
|
|
2
|
+
import { normalizeHttpUrl, postJson, truncateUtf8 } from "./http.js";
|
|
3
|
+
|
|
4
|
+
// Official contract: https://bark.day.app/#/tutorial and Finb/bark-server at
|
|
5
|
+
// 640deaa151ddf79193202927b35ca2f14f65ee1d: docs/API_V2.md, route_push.go,
|
|
6
|
+
// router.go, and route_auth.go. POST /push accepts JSON; numeric code 200 means acceptance.
|
|
7
|
+
// Native Basic authentication is not supported. Keys and messages stay in the JSON body.
|
|
8
|
+
export function createBarkProvider(fetcher: typeof fetch = fetch): NotificationProvider {
|
|
9
|
+
return {
|
|
10
|
+
id: "bark",
|
|
11
|
+
label: "Bark",
|
|
12
|
+
validate(value) {
|
|
13
|
+
if (!isObject(value) || value.provider !== "bark") return undefined;
|
|
14
|
+
if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
|
|
15
|
+
const serverUrl = normalizeHttpUrl(value.serverUrl);
|
|
16
|
+
// Local printable-ASCII safety limit (no spaces), not an upstream device-key format claim.
|
|
17
|
+
if (!serverUrl || typeof value.deviceKey !== "string" || !/^[\x21-\x7e]{1,512}$/.test(value.deviceKey))
|
|
18
|
+
return undefined;
|
|
19
|
+
return { provider: "bark", label: value.label, serverUrl, deviceKey: value.deviceKey };
|
|
20
|
+
},
|
|
21
|
+
async send(destination, notification, signal): Promise<DeliveryResult> {
|
|
22
|
+
if (signal.aborted) return { state: "cancelled", code: "cancelled" };
|
|
23
|
+
const valid = this.validate(destination);
|
|
24
|
+
if (valid?.provider !== "bark") return { state: "failed", code: "invalid-destination" };
|
|
25
|
+
// Local limits, not upstream limits: title 256 and body 2048 UTF-8 bytes.
|
|
26
|
+
// Keep encoded {title,body} within 3000 bytes to leave room in APNs' default
|
|
27
|
+
// 4096-byte envelope. Count JSON escapes, not only decoded text bytes.
|
|
28
|
+
const title = truncateUtf8(notification.title, 256);
|
|
29
|
+
let remaining = 3000 - Buffer.byteLength(JSON.stringify({ title, body: "" }), "utf8");
|
|
30
|
+
let body = "";
|
|
31
|
+
for (const point of truncateUtf8(notification.body, 2048)) {
|
|
32
|
+
const encodedBytes = Buffer.byteLength(JSON.stringify(point), "utf8") - 2;
|
|
33
|
+
if (encodedBytes > remaining) break;
|
|
34
|
+
body += point;
|
|
35
|
+
remaining -= encodedBytes;
|
|
36
|
+
}
|
|
37
|
+
const result = await postJson(
|
|
38
|
+
`${valid.serverUrl}/push`,
|
|
39
|
+
{ device_key: valid.deviceKey, title, body },
|
|
40
|
+
signal,
|
|
41
|
+
fetcher,
|
|
42
|
+
);
|
|
43
|
+
if (result.state !== "response") return result;
|
|
44
|
+
if (result.status !== 200 || !isObject(result.body) || typeof result.body.code !== "number")
|
|
45
|
+
return { state: "failed", code: "response" };
|
|
46
|
+
return result.body.code === 200 ? { state: "accepted" } : { state: "failed", code: "api" };
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
2
|
+
import { type DeliveryResult, isObject, type NotificationProvider } from "../provider.js";
|
|
3
|
+
import { clipText } from "../text.js";
|
|
4
|
+
import { postJson } from "./http.js";
|
|
5
|
+
|
|
6
|
+
// https://discord.com/developers/docs/resources/webhook#execute-webhook
|
|
7
|
+
// https://discord.com/developers/docs/resources/message#allowed-mentions-object
|
|
8
|
+
// Official OpenAPI: discord/discord-api-spec@ed014089afa986f2b532ae081c456a85de074d0c.
|
|
9
|
+
function isSnowflake(value: unknown): value is string {
|
|
10
|
+
return (
|
|
11
|
+
typeof value === "string" &&
|
|
12
|
+
!/\s/.test(value) &&
|
|
13
|
+
/^[1-9][0-9]{0,19}$/.test(value) &&
|
|
14
|
+
BigInt(value) <= 18446744073709551615n
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Match the literal official endpoint; do not accept URL parser normalization aliases. */
|
|
19
|
+
export function validateDiscordWebhookUrl(value: unknown): value is string {
|
|
20
|
+
if (typeof value !== "string" || value.length > 2048 || /[\s\\\p{Cc}]/u.test(value)) return false;
|
|
21
|
+
const match = /^https:\/\/discord\.com\/api\/(?:v10\/)?webhooks\/([1-9][0-9]{0,19})\/[-_A-Za-z0-9]+$/.exec(value);
|
|
22
|
+
return match !== null && isSnowflake(match[1]);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function createDiscordProvider(fetcher: typeof fetch = fetch): NotificationProvider {
|
|
26
|
+
return {
|
|
27
|
+
id: "discord",
|
|
28
|
+
label: "Discord",
|
|
29
|
+
validate(value) {
|
|
30
|
+
if (!isObject(value) || value.provider !== "discord") return undefined;
|
|
31
|
+
if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
|
|
32
|
+
if (!validateDiscordWebhookUrl(value.webhookUrl)) return undefined;
|
|
33
|
+
return { provider: "discord", label: value.label, webhookUrl: value.webhookUrl };
|
|
34
|
+
},
|
|
35
|
+
async send(destination, notification, signal): Promise<DeliveryResult> {
|
|
36
|
+
if (signal.aborted) return { state: "cancelled", code: "cancelled" };
|
|
37
|
+
const valid = this.validate(destination);
|
|
38
|
+
if (valid?.provider !== "discord") return { state: "failed", code: "invalid-destination" };
|
|
39
|
+
const text = `${notification.title}\n${notification.body}`.split("\n").map(sanitizeTerminalText).join("\n");
|
|
40
|
+
const result = await postJson(
|
|
41
|
+
`${valid.webhookUrl}?wait=true`,
|
|
42
|
+
{
|
|
43
|
+
content: clipText(text.trim() ? text : "Pi notification", 2000),
|
|
44
|
+
// Enforce this for direct callers, not only for metadata produced by the coordinator.
|
|
45
|
+
allowed_mentions: { parse: [] },
|
|
46
|
+
flags: 4, // SUPPRESS_EMBEDS, not SUPPRESS_NOTIFICATIONS (4096).
|
|
47
|
+
},
|
|
48
|
+
signal,
|
|
49
|
+
fetcher,
|
|
50
|
+
{
|
|
51
|
+
// Discord's required bot User-Agent syntax. 1.0 is the adapter version, not the package version.
|
|
52
|
+
"User-Agent": "DiscordBot (https://github.com/narumiruna/pi-extensions, 1.0)",
|
|
53
|
+
},
|
|
54
|
+
);
|
|
55
|
+
if (result.state !== "response") return result;
|
|
56
|
+
const body = result.body;
|
|
57
|
+
return result.status === 200 &&
|
|
58
|
+
isObject(body) &&
|
|
59
|
+
isSnowflake(body.id) &&
|
|
60
|
+
isSnowflake(body.channel_id) &&
|
|
61
|
+
Number.isInteger(body.type)
|
|
62
|
+
? { state: "accepted" }
|
|
63
|
+
: { state: "failed", code: "response" };
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { type DeliveryResult, isObject, type NotificationProvider } from "../provider.js";
|
|
2
|
+
|
|
3
|
+
const TIMEOUT_MS = 10_000;
|
|
4
|
+
const MAX_RESPONSE_BYTES = 65_536;
|
|
5
|
+
|
|
6
|
+
/** Accept self-hosted HTTP(S), including reverse-proxy paths, but no URL credentials. */
|
|
7
|
+
export function normalizeGotifyUrl(value: unknown): string | undefined {
|
|
8
|
+
if (typeof value !== "string" || value.length > 2048 || /[\s\\?#\p{Cc}]/u.test(value)) return undefined;
|
|
9
|
+
try {
|
|
10
|
+
const url = new URL(value);
|
|
11
|
+
if (!/^https?:\/\/[^/@]+(?:\/|$)/i.test(value) || url.username || url.password) return undefined;
|
|
12
|
+
const normalized = url.href.replace(/\/+$/, "");
|
|
13
|
+
return normalized.length <= 2048 ? normalized : undefined;
|
|
14
|
+
} catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Application-token auth only; no redirects, retries, Markdown extras, or client subscriptions. */
|
|
20
|
+
export function createGotifyProvider(fetcher: typeof fetch = fetch): NotificationProvider {
|
|
21
|
+
return {
|
|
22
|
+
id: "gotify",
|
|
23
|
+
label: "Gotify",
|
|
24
|
+
validate(value) {
|
|
25
|
+
if (!isObject(value) || value.provider !== "gotify") return undefined;
|
|
26
|
+
if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
|
|
27
|
+
const serverUrl = normalizeGotifyUrl(value.serverUrl);
|
|
28
|
+
if (!serverUrl || typeof value.appToken !== "string" || !/^[\x21-\x7e]{1,512}$/.test(value.appToken))
|
|
29
|
+
return undefined;
|
|
30
|
+
if (value.priority !== undefined && !Number.isSafeInteger(value.priority)) return undefined;
|
|
31
|
+
return {
|
|
32
|
+
provider: "gotify",
|
|
33
|
+
label: value.label,
|
|
34
|
+
serverUrl,
|
|
35
|
+
appToken: value.appToken,
|
|
36
|
+
priority: value.priority === undefined ? undefined : Number(value.priority),
|
|
37
|
+
};
|
|
38
|
+
},
|
|
39
|
+
async send(destination, notification, signal): Promise<DeliveryResult> {
|
|
40
|
+
if (signal.aborted) return { state: "cancelled", code: "cancelled" };
|
|
41
|
+
// Validate again for direct callers and use the normalized reverse-proxy base path.
|
|
42
|
+
const valid = this.validate(destination);
|
|
43
|
+
if (valid?.provider !== "gotify") return { state: "failed", code: "invalid-destination" };
|
|
44
|
+
const timeout = new AbortController();
|
|
45
|
+
const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);
|
|
46
|
+
const combined = AbortSignal.any([signal, timeout.signal]);
|
|
47
|
+
try {
|
|
48
|
+
const response = await fetcher(`${valid.serverUrl}/message`, {
|
|
49
|
+
method: "POST",
|
|
50
|
+
redirect: "error",
|
|
51
|
+
signal: combined,
|
|
52
|
+
headers: { "content-type": "application/json", "X-Gotify-Key": valid.appToken },
|
|
53
|
+
body: JSON.stringify({
|
|
54
|
+
title: notification.title,
|
|
55
|
+
message: notification.body,
|
|
56
|
+
...(valid.priority === undefined ? {} : { priority: valid.priority }),
|
|
57
|
+
}),
|
|
58
|
+
});
|
|
59
|
+
combined.throwIfAborted();
|
|
60
|
+
if (!response.ok) {
|
|
61
|
+
await response.body?.cancel().catch(() => {});
|
|
62
|
+
combined.throwIfAborted();
|
|
63
|
+
const retry = response.headers.get("retry-after");
|
|
64
|
+
return {
|
|
65
|
+
state: "failed",
|
|
66
|
+
code: response.status === 429 ? "rate-limit" : "http",
|
|
67
|
+
...(response.status === 429 &&
|
|
68
|
+
retry &&
|
|
69
|
+
/^\d+$/.test(retry) &&
|
|
70
|
+
Number.isSafeInteger(Number(retry)) &&
|
|
71
|
+
Number(retry) > 0
|
|
72
|
+
? { retryAfterSeconds: Number(retry) }
|
|
73
|
+
: {}),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
const reader = response.body?.getReader();
|
|
77
|
+
if (!reader) return { state: "failed", code: "response" };
|
|
78
|
+
let length = 0;
|
|
79
|
+
const chunks: Uint8Array[] = [];
|
|
80
|
+
try {
|
|
81
|
+
while (true) {
|
|
82
|
+
combined.throwIfAborted();
|
|
83
|
+
const part = await reader.read();
|
|
84
|
+
combined.throwIfAborted();
|
|
85
|
+
if (part.done) break;
|
|
86
|
+
length += part.value.byteLength;
|
|
87
|
+
if (length > MAX_RESPONSE_BYTES) break;
|
|
88
|
+
chunks.push(part.value);
|
|
89
|
+
}
|
|
90
|
+
} finally {
|
|
91
|
+
await reader.cancel().catch(() => {});
|
|
92
|
+
reader.releaseLock();
|
|
93
|
+
}
|
|
94
|
+
combined.throwIfAborted();
|
|
95
|
+
if (length > MAX_RESPONSE_BYTES) return { state: "failed", code: "response" };
|
|
96
|
+
let body: unknown;
|
|
97
|
+
try {
|
|
98
|
+
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
99
|
+
} catch {
|
|
100
|
+
return { state: "failed", code: "response" };
|
|
101
|
+
}
|
|
102
|
+
// The documented success is a Message, not merely any HTTP 2xx response.
|
|
103
|
+
return isObject(body) &&
|
|
104
|
+
Number.isSafeInteger(body.id) &&
|
|
105
|
+
Number(body.id) > 0 &&
|
|
106
|
+
Number.isSafeInteger(body.appid) &&
|
|
107
|
+
Number(body.appid) > 0 &&
|
|
108
|
+
typeof body.message === "string" &&
|
|
109
|
+
typeof body.date === "string" &&
|
|
110
|
+
Number.isFinite(Date.parse(body.date))
|
|
111
|
+
? { state: "accepted" }
|
|
112
|
+
: { state: "failed", code: "response" };
|
|
113
|
+
} catch {
|
|
114
|
+
if (signal.aborted) return { state: "cancelled", code: "cancelled" };
|
|
115
|
+
return { state: "failed", code: timeout.signal.aborted ? "timeout" : "network" };
|
|
116
|
+
} finally {
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { DeliveryResult } from "../provider.js";
|
|
2
|
+
|
|
3
|
+
const TIMEOUT_MS = 10_000;
|
|
4
|
+
const MAX_RESPONSE_BYTES = 65_536;
|
|
5
|
+
|
|
6
|
+
/** Explicit HTTP(S) endpoints may reach local networks; never accept URL credentials or query auth. */
|
|
7
|
+
export function normalizeHttpUrl(value: unknown): string | undefined {
|
|
8
|
+
if (typeof value !== "string" || value.length > 2048 || /[\s\\?#\p{Cc}]/u.test(value)) return undefined;
|
|
9
|
+
if (!/^https?:\/\/[^/@]+(?:\/|$)/i.test(value)) return undefined;
|
|
10
|
+
try {
|
|
11
|
+
// Reject encoded controls, backslashes, and malformed percent escapes before URL parsing.
|
|
12
|
+
if (/[\\\p{Cc}]/u.test(decodeURIComponent(value))) return undefined;
|
|
13
|
+
const raw = /^https?:\/\/([^/]+)(\/.*)?$/i.exec(value);
|
|
14
|
+
if (
|
|
15
|
+
!raw ||
|
|
16
|
+
decodeURIComponent(raw[2] ?? "")
|
|
17
|
+
.split("/")
|
|
18
|
+
.some((part) => part === "." || part === "..")
|
|
19
|
+
)
|
|
20
|
+
return undefined;
|
|
21
|
+
const url = new URL(value);
|
|
22
|
+
if (url.username || url.password || !url.hostname) return undefined;
|
|
23
|
+
// WHATWG rewrites numeric IPv4 aliases (hex, octal, shortened, or integer) to a different host spelling.
|
|
24
|
+
// Accept explicit private addresses, but require canonical dotted-decimal IPv4 input.
|
|
25
|
+
const rawHost = raw[1]?.split(":")[0];
|
|
26
|
+
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(url.hostname) && rawHost !== url.hostname) return undefined;
|
|
27
|
+
const normalized = url.href.replace(/\/+$/, "");
|
|
28
|
+
return normalized.length <= 2048 ? normalized : undefined;
|
|
29
|
+
} catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Keep complete Unicode code points within a UTF-8 byte budget. */
|
|
35
|
+
export function truncateUtf8(value: string, maxBytes: number): string {
|
|
36
|
+
let bytes = 0;
|
|
37
|
+
let result = "";
|
|
38
|
+
for (const point of value) {
|
|
39
|
+
bytes += Buffer.byteLength(point, "utf8");
|
|
40
|
+
if (bytes > maxBytes) break;
|
|
41
|
+
result += point;
|
|
42
|
+
}
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** POST once. A response is transport acceptance only; the provider checks its service contract. */
|
|
47
|
+
export async function postJson(
|
|
48
|
+
url: string,
|
|
49
|
+
payload: unknown,
|
|
50
|
+
signal: AbortSignal,
|
|
51
|
+
fetcher: typeof fetch = fetch,
|
|
52
|
+
headers: Record<string, string> = {},
|
|
53
|
+
): Promise<{ state: "response"; body: unknown; status: number } | DeliveryResult> {
|
|
54
|
+
if (signal.aborted) return { state: "cancelled", code: "cancelled" };
|
|
55
|
+
const timeout = new AbortController();
|
|
56
|
+
const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);
|
|
57
|
+
const combined = AbortSignal.any([signal, timeout.signal]);
|
|
58
|
+
let rejectAbort!: (reason: unknown) => void;
|
|
59
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
60
|
+
rejectAbort = reject;
|
|
61
|
+
});
|
|
62
|
+
const onAbort = () => rejectAbort(combined.reason);
|
|
63
|
+
combined.addEventListener("abort", onAbort, { once: true });
|
|
64
|
+
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
|
65
|
+
try {
|
|
66
|
+
const fetching = fetcher(url, {
|
|
67
|
+
method: "POST",
|
|
68
|
+
redirect: "error",
|
|
69
|
+
signal: combined,
|
|
70
|
+
headers: { "content-type": "application/json", ...headers },
|
|
71
|
+
body: JSON.stringify(payload),
|
|
72
|
+
}).then((response) => {
|
|
73
|
+
// An injected fetch can ignore abort and settle after this request has ended.
|
|
74
|
+
if (combined.aborted) void response.body?.cancel().catch(() => {});
|
|
75
|
+
return response;
|
|
76
|
+
});
|
|
77
|
+
const response = await Promise.race([fetching, aborted]);
|
|
78
|
+
combined.throwIfAborted();
|
|
79
|
+
if (!response.ok) {
|
|
80
|
+
void response.body?.cancel().catch(() => {});
|
|
81
|
+
const retry = response.headers.get("retry-after");
|
|
82
|
+
return {
|
|
83
|
+
state: "failed",
|
|
84
|
+
code: response.status === 429 ? "rate-limit" : "http",
|
|
85
|
+
...(response.status === 429 &&
|
|
86
|
+
retry &&
|
|
87
|
+
/^\d+$/.test(retry) &&
|
|
88
|
+
Number.isSafeInteger(Number(retry)) &&
|
|
89
|
+
Number(retry) > 0
|
|
90
|
+
? { retryAfterSeconds: Number(retry) }
|
|
91
|
+
: {}),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
reader = response.body?.getReader();
|
|
95
|
+
const chunks: Uint8Array[] = [];
|
|
96
|
+
let length = 0;
|
|
97
|
+
while (reader) {
|
|
98
|
+
const part = await Promise.race([reader.read(), aborted]);
|
|
99
|
+
combined.throwIfAborted();
|
|
100
|
+
if (part.done) break;
|
|
101
|
+
length += part.value.byteLength;
|
|
102
|
+
if (length > MAX_RESPONSE_BYTES) return { state: "failed", code: "response" };
|
|
103
|
+
if (part.value.byteLength) chunks.push(part.value);
|
|
104
|
+
}
|
|
105
|
+
let body: unknown;
|
|
106
|
+
try {
|
|
107
|
+
body = JSON.parse(Buffer.concat(chunks, length).toString("utf8"));
|
|
108
|
+
} catch {
|
|
109
|
+
// Empty/non-JSON success is valid for some endpoints, but not for service-specific JSON APIs.
|
|
110
|
+
body = undefined;
|
|
111
|
+
}
|
|
112
|
+
return { state: "response", body, status: response.status };
|
|
113
|
+
} catch {
|
|
114
|
+
if (signal.aborted) return { state: "cancelled", code: "cancelled" };
|
|
115
|
+
return { state: "failed", code: timeout.signal.aborted ? "timeout" : "network" };
|
|
116
|
+
} finally {
|
|
117
|
+
if (reader) {
|
|
118
|
+
// Stream cancellation itself can stall. Do not await an untrusted underlying source.
|
|
119
|
+
void reader.cancel().catch(() => {});
|
|
120
|
+
reader.releaseLock();
|
|
121
|
+
}
|
|
122
|
+
combined.removeEventListener("abort", onAbort);
|
|
123
|
+
clearTimeout(timer);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -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
|
+
}
|