@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/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
- const lines = [
43
- `Computer: ${safeText(hostname())}`,
44
- `Session: ${data.sessionName ? `${safeText(data.sessionName)} ` : ""}(${safeText(data.sessionId)})`,
45
- `Workspace: ${displayPath(data.cwd)}`,
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
- lines.push(`Repository: ${repository}`, `Worktree: ${displayPath(root)}`);
57
- if (branch) lines.push(`Branch: ${safeText(branch === "HEAD" ? `detached ${detached ?? "HEAD"}` : branch)}`);
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
- lines.push(
60
- `Elapsed: ${Math.max(0, Math.floor((data.settledAt - data.startedAt) / 1000))}s`,
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: lines.join("\n"),
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("Telegram notification failed. Open /notify → Status for a safe error code.", "warning");
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 Telegram notifications and inactivity reminders",
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,93 @@ export interface TelegramDestination {
6
6
  messageThreadId?: number;
7
7
  }
8
8
 
9
- export type Destination = TelegramDestination;
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 TeamsDestination {
53
+ provider: "teams";
54
+ label: string;
55
+ webhookUrl: string;
56
+ }
57
+
58
+ export interface LineDestination {
59
+ provider: "line";
60
+ label: string;
61
+ channelAccessToken: string;
62
+ recipientId: string;
63
+ }
64
+
65
+ export interface WebhookDestination {
66
+ provider: "webhook";
67
+ label: string;
68
+ webhookUrl: string;
69
+ bearerToken?: string;
70
+ }
71
+
72
+ export type Destination =
73
+ | TelegramDestination
74
+ | GotifyDestination
75
+ | SlackDestination
76
+ | NtfyDestination
77
+ | PushoverDestination
78
+ | DiscordDestination
79
+ | BarkDestination
80
+ | WebhookDestination
81
+ | LineDestination
82
+ | TeamsDestination;
83
+
84
+ export interface BodyEmphasis {
85
+ style: "bold" | "monospace";
86
+ /** Offset and length in UTF-16 code units of the sanitized body. */
87
+ offset: number;
88
+ length: number;
89
+ }
10
90
 
11
91
  export interface Notification {
12
92
  id: string;
13
93
  title: string;
14
94
  body: string;
95
+ bodyEmphasis?: BodyEmphasis[];
15
96
  settledAt: number;
16
97
  }
17
98
 
@@ -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,91 @@
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
+ // Verified 2026-10-18: https://developers.line.biz/en/reference/messaging-api/#send-push-message
7
+ // https://developers.line.biz/en/docs/messaging-api/text-character-count/: 5,000 UTF-16 units.
8
+ // https://developers.line.biz/en/docs/basics/channel-access-token/: tokens are opaque.
9
+ // RFC 6750 section 2.1 defines Bearer syntax; 8,192 is a local cap, not a LINE token limit.
10
+ const MAX_TOKEN_LENGTH = 8192;
11
+
12
+ function plainText(text: string): string {
13
+ return text.split("\n").map(sanitizeTerminalText).join("\n");
14
+ }
15
+
16
+ function acceptedBody(body: unknown): boolean {
17
+ if (!isObject(body)) return false;
18
+ // Legacy {}: https://github.com/line/line-bot-sdk-nodejs/blob/master/test/line-bot-client.spec.ts
19
+ // Current schema: https://github.com/line/line-openapi/blob/main/messaging-api.yml
20
+ if (Object.keys(body).length === 0) return true;
21
+ // Current reference uses Number for id; official line-openapi and its example use String.
22
+ return (
23
+ Array.isArray(body.sentMessages) &&
24
+ body.sentMessages.length >= 1 &&
25
+ body.sentMessages.length <= 5 &&
26
+ body.sentMessages.every(
27
+ (message) =>
28
+ isObject(message) &&
29
+ ((typeof message.id === "string" && message.id.length > 0) ||
30
+ (typeof message.id === "number" && Number.isInteger(message.id) && message.id >= 0)) &&
31
+ (message.quoteToken === undefined || typeof message.quoteToken === "string"),
32
+ )
33
+ );
34
+ }
35
+
36
+ /** One normal text push; HTTP acceptance does not prove recipient delivery. */
37
+ export function createLineProvider(fetcher: typeof fetch = fetch): NotificationProvider {
38
+ return {
39
+ id: "line",
40
+ label: "LINE",
41
+ validate(value) {
42
+ if (!isObject(value) || value.provider !== "line") return undefined;
43
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
44
+ if (
45
+ typeof value.channelAccessToken !== "string" ||
46
+ value.channelAccessToken.length > MAX_TOKEN_LENGTH ||
47
+ /\s/u.test(value.channelAccessToken) ||
48
+ !/^[A-Za-z0-9._~+/-]+=*$/u.test(value.channelAccessToken)
49
+ )
50
+ return undefined;
51
+ // https://developers.line.biz/en/docs/messaging-api/getting-user-ids/: U + 32 lowercase hex.
52
+ // The push reference's webhook source examples use C/R prefixes for group/room IDs.
53
+ // Group/room syntax is not specified: printable ASCII and 128 suffix characters
54
+ // are local safety bounds, not a claimed service grammar.
55
+ if (
56
+ typeof value.recipientId !== "string" ||
57
+ value.recipientId.length > 129 ||
58
+ /\s/u.test(value.recipientId) ||
59
+ !/^(?:U[0-9a-f]{32}|[CR][!-~]{1,128})$/u.test(value.recipientId)
60
+ )
61
+ return undefined;
62
+ return {
63
+ provider: "line",
64
+ label: value.label,
65
+ channelAccessToken: value.channelAccessToken,
66
+ recipientId: value.recipientId,
67
+ };
68
+ },
69
+ async send(destination, notification, signal): Promise<DeliveryResult> {
70
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
71
+ const valid = this.validate(destination);
72
+ if (valid?.provider !== "line") return { state: "failed", code: "invalid-destination" };
73
+ const result = await postJson(
74
+ "https://api.line.me/v2/bot/message/push",
75
+ {
76
+ to: valid.recipientId,
77
+ // No mention/emoji objects, substitutions, formatting, or silent-delivery option.
78
+ // LINE clients can still auto-link literal URLs; this does not promise link suppression.
79
+ messages: [{ type: "text", text: clipText(plainText(`${notification.title}\n${notification.body}`), 5000) }],
80
+ },
81
+ signal,
82
+ fetcher,
83
+ { Authorization: `Bearer ${valid.channelAccessToken}` },
84
+ );
85
+ if (result.state !== "response") return result;
86
+ return result.status === 200 && acceptedBody(result.body)
87
+ ? { state: "accepted" }
88
+ : { state: "failed", code: "response" };
89
+ },
90
+ };
91
+ }