my-durable 0.0.40 → 0.0.41

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,947 @@
1
+ /**
2
+ * Device-side notification delivery fan-out — "Notification delivery fan-out",
3
+ * Wave 2 of docs/host-project-checklist.md.
4
+ *
5
+ * A device that hosts durable sessions already knows when something happens
6
+ * (a turn failed, a schedule ran, a session finished). This module is the piece
7
+ * that can *tell someone* without the hub in the middle: one event in, zero or
8
+ * more configured sinks out — a generic `webhook` (JSON POST) and `ntfy`
9
+ * (a push to an ntfy server, `<server>/<topic>`).
10
+ *
11
+ * Modelled on orca's `notification-delivery-service.ts:15-49` (tray → mobile →
12
+ * desktop fan-out behind a burst cooldown) and piggery's `setup notify` hooks
13
+ * (`docs/reference.md:15`, desktop/herdr/ntfy). Two deliberate adaptations:
14
+ * sinks are *records in a file* instead of a fixed tray/mobile/desktop ladder,
15
+ * so the operator opts in per target; and the cooldown is keyed per sink **and
16
+ * per event kind**, because "the disk is full" arriving ten times in a burst is
17
+ * one notification while "backup ok" and "backup failed" are not the same news.
18
+ *
19
+ * The file handling is lifted from `projects.ts` on purpose — same atomic
20
+ * temp+rename, same `.bak` rolling backup, same "unreadable file is moved aside,
21
+ * never overwritten" rule, same 0600/0700 perms, same serialised mutation queue
22
+ * and the same typed errors. Delivery state (`lastDeliveryAt`, `lastError`,
23
+ * `lastStatus`) lives in that same file: a sink whose webhook has been dead for a
24
+ * week should say so on the next boot, not forget it.
25
+ *
26
+ * `deliver()` never throws. A dead webhook must not break a session turn — the
27
+ * caller gets a per-sink `failed` result and the reason lands on the record.
28
+ *
29
+ * Everything here is Node builtins only: `node:fs/promises`, `node:crypto`,
30
+ * `node:path`. No shell, no zod, no HTTP client of its own — the `fetchImpl`
31
+ * seam is injected (default `globalThis.fetch`).
32
+ */
33
+ import { randomBytes } from "node:crypto";
34
+ import { chmod, copyFile, readFile, rename, unlink, writeFile } from "node:fs/promises";
35
+ import { dirname, resolve } from "node:path";
36
+ import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
37
+
38
+ /** Bumped only when the on-disk shape changes; `migrate` owns the upgrade path. */
39
+ export const NOTIFY_REGISTRY_VERSION = 1;
40
+
41
+ /** One delivery per (sink, event kind) per window. orca's `NOTIFICATION_COOLDOWN_MS` lesson, per kind. */
42
+ export const DEFAULT_COOLDOWN_MS = 10_000;
43
+ /** A notification is not worth holding a session turn open for; the sink is retried on the next event. */
44
+ export const DEFAULT_TIMEOUT_MS = 5_000;
45
+
46
+ /** A human label, not a description. */
47
+ export const MAX_LABEL_LENGTH = 60;
48
+ /** ntfy turns more than this into noise in a phone's status bar. */
49
+ export const MAX_TAGS = 5;
50
+ /** ntfy tags are short words or emoji shortcodes. */
51
+ export const MAX_TAG_LENGTH = 20;
52
+ /** Filter patterns are hand-written; past this the list is a routing table, not a subscription. */
53
+ export const MAX_EVENT_PATTERNS = 32;
54
+ /** `lastError` is shown in a UI row; a stack of nested fetch causes helps nobody there. */
55
+ const MAX_ERROR_LENGTH = 300;
56
+
57
+ /** Patterns are event kinds: loose tokens, optionally ending in `.*`. `*` alone means "everything". */
58
+ const EVENT_PATTERN = /^(\*|[A-Za-z0-9][A-Za-z0-9._-]*(\.\*)?)$/;
59
+ /** ntfy joins tags with commas, so a tag cannot contain one. */
60
+ const TAGS_FORBIDDEN = /[\s,]/;
61
+
62
+ export type SinkKind = "webhook" | "ntfy";
63
+
64
+ /** ntfy's five priorities, spelled the way its HTTP API spells them. */
65
+ export type NotifyPriority = "min" | "low" | "default" | "high" | "max";
66
+
67
+ const PRIORITIES: readonly NotifyPriority[] = ["min", "low", "default", "high", "max"];
68
+
69
+ /**
70
+ * One event to fan out. `kind` is the filter key (free-form — the device emits
71
+ * `session.failed`, `schedule.ok`, `schedule.failed`, `test` today), `title` and
72
+ * `body` are what a human reads, and `data` is extra structure a webhook
73
+ * consumer may want.
74
+ */
75
+ export interface NotifyEvent {
76
+ /** "session.failed" | "schedule.ok" | "schedule.failed" | "test" — free-form, used for filtering. */
77
+ kind: string;
78
+ title: string;
79
+ body: string;
80
+ /** Extra structured fields; delivered as-is in the webhook JSON. */
81
+ data?: Record<string, unknown>;
82
+ }
83
+
84
+ /** What `create` takes and what `update` patches. `id`/timestamps belong to the registry. */
85
+ export interface SinkInput {
86
+ kind: SinkKind;
87
+ /** `http(s)://…`. For an `ntfy` sink the path *is* the topic (`https://ntfy.sh/dpi`). */
88
+ url: string;
89
+ /** Defaults to `true`: a sink that exists is a sink the operator asked for. */
90
+ enabled?: boolean;
91
+ /** Event kinds this sink wants; absent or empty means every kind. */
92
+ events?: string[];
93
+ label?: string;
94
+ /** ntfy only: the priority header. Absent lets ntfy decide (`default`). */
95
+ priority?: NotifyPriority;
96
+ /** ntfy only: `Tags` header entries. */
97
+ tags?: string[];
98
+ }
99
+
100
+ /**
101
+ * One configured sink plus the outcome of its last attempt. Delivery state is
102
+ * written by `deliver` — it is not part of `SinkInput`.
103
+ */
104
+ export interface SinkRecord {
105
+ /** `snk_<12 hex>`; stable for the life of the sink. */
106
+ id: string;
107
+ kind: SinkKind;
108
+ /** Normalised: no trailing slash on the path, no userinfo (both are rejected at write time). */
109
+ url: string;
110
+ enabled: boolean;
111
+ /** Absent/empty = every event; otherwise exact kind match or a `prefix.*` wildcard. */
112
+ events: string[];
113
+ label?: string;
114
+ priority?: NotifyPriority;
115
+ tags?: string[];
116
+ createdAt: number;
117
+ updatedAt: number;
118
+ /** When the last delivery *attempt* finished — success or failure. */
119
+ lastDeliveryAt?: number;
120
+ /** Why that attempt failed, as one line (≤ 300 chars). Cleared by a success. */
121
+ lastError?: string;
122
+ /** HTTP status of that attempt; absent when the request never got a response. */
123
+ lastStatus?: number;
124
+ }
125
+
126
+ /** The on-disk document. `version` exists so a future shape can be migrated instead of discarded. */
127
+ export interface NotifyRegistryFile {
128
+ version: number;
129
+ sinks: SinkRecord[];
130
+ }
131
+
132
+ /** One sink's verdict for one event. `deliver` returns these in sink order. */
133
+ export interface DeliveryResult {
134
+ id: string;
135
+ kind: SinkKind;
136
+ status: "sent" | "skipped" | "failed";
137
+ /** `filtered` | `cooldown` for skips, `HTTP 500` / the fetch error for failures. */
138
+ detail?: string;
139
+ /** Wall-clock duration of the request, on attempts that actually left the device. */
140
+ ms?: number;
141
+ }
142
+
143
+ /** The sliver of `fetch` this module uses — injected so tests never open a socket. */
144
+ export interface FetchResponseLike {
145
+ readonly ok: boolean;
146
+ readonly status: number;
147
+ }
148
+
149
+ export type FetchLike = (
150
+ url: string,
151
+ init: {
152
+ method: string;
153
+ headers: Record<string, string>;
154
+ body: string;
155
+ signal?: AbortSignal;
156
+ },
157
+ ) => Promise<FetchResponseLike>;
158
+
159
+ export type NotifySinkErrorCode = "invalid" | "not_found";
160
+
161
+ /** Typed failure so routes can answer 400 (`invalid`) or 404 (`not_found`) without string matching. */
162
+ export class NotifySinkError extends Error {
163
+ readonly code: NotifySinkErrorCode;
164
+
165
+ constructor(code: NotifySinkErrorCode, message: string) {
166
+ super(message);
167
+ this.name = "NotifySinkError";
168
+ this.code = code;
169
+ }
170
+ }
171
+
172
+ export interface NotifySinksOptions {
173
+ /** Where unreadable-file / recovery / delivery-write notices go. Defaults to `console.warn`. */
174
+ warn?: (message: string, error?: unknown) => void;
175
+ /** Injectable clock (epoch ms) — tests pin timestamps and cooldowns instead of sleeping. */
176
+ now?: () => number;
177
+ /** Defaults to `globalThis.fetch`. */
178
+ fetchImpl?: FetchLike;
179
+ /** Minimum gap between two deliveries of the same event kind to one sink. */
180
+ cooldownMs?: number;
181
+ /** Per-request timeout handed to `AbortSignal.timeout`. */
182
+ timeoutMs?: number;
183
+ /**
184
+ * Allow `localhost`, loopback, link-local and private-range hosts. Default
185
+ * `false`: a sink URL is user input, and a device that will POST to
186
+ * `http://169.254.169.254/` on request is an SSRF primitive. The reverse case
187
+ * is real, though — an ntfy server on the LAN is the common self-hosted
188
+ * setup — so the operator can turn it on deliberately.
189
+ */
190
+ allowPrivateHosts?: boolean;
191
+ }
192
+
193
+ const invalid = (message: string) => new NotifySinkError("invalid", message);
194
+ const notFound = (id: string) => new NotifySinkError("not_found", `no notification sink ${id}`);
195
+ const describeError = (error: unknown) => (error instanceof Error ? error.message : String(error));
196
+ const defaultWarn = (message: string, error?: unknown) =>
197
+ console.warn(`[notify] ${message}`, error === undefined ? "" : describeError(error));
198
+
199
+ const clone = (record: SinkRecord): SinkRecord => ({
200
+ ...record,
201
+ events: [...record.events],
202
+ ...(record.tags ? { tags: [...record.tags] } : {}),
203
+ });
204
+
205
+ /** `snk_` + 12 hex: short enough for a URL, wide enough that collisions are not a real risk. */
206
+ export function newSinkId(): string {
207
+ return `snk_${randomBytes(6).toString("hex")}`;
208
+ }
209
+
210
+ const isKind = (value: unknown): value is SinkKind => value === "webhook" || value === "ntfy";
211
+ const isPriority = (value: unknown): value is NotifyPriority =>
212
+ typeof value === "string" && (PRIORITIES as readonly string[]).includes(value);
213
+ const nonEmptyString = (value: unknown): string | undefined =>
214
+ typeof value === "string" && value.trim() ? value.trim() : undefined;
215
+
216
+ /**
217
+ * Is this host one the device must not POST to by default? Judged on the literal
218
+ * host in the URL — `localhost`/`.localhost`, decimal-encoded IPv4, every
219
+ * private/loopback/link-local/CGNAT range, IPv6 `::`/`::1`/`fc00::/7`/`fe80::/10`
220
+ * and IPv4-mapped forms of the above.
221
+ *
222
+ * Known limit, on purpose: no DNS is resolved here (this module must not do I/O
223
+ * to validate input). A public-looking name that resolves to `127.0.0.1` passes
224
+ * the check — the flag exists to stop the obvious cases, not to be a firewall.
225
+ */
226
+ export function isPrivateHost(hostname: string): boolean {
227
+ const host = hostname.trim().toLowerCase().replace(/^\[|\]$/g, "");
228
+ if (!host) return true;
229
+ if (host === "localhost" || host.endsWith(".localhost")) return true;
230
+ if (/^\d+$/.test(host)) return true; // decimal-encoded IPv4 (2130706433 → 127.0.0.1)
231
+ if (isPrivateIPv4(host)) return true;
232
+ if (host.includes(":")) {
233
+ if (host === "::" || host === "::1") return true;
234
+ if (/^f[cd][0-9a-f]{2}:/.test(host)) return true; // fc00::/7 unique-local
235
+ if (/^fe[89ab][0-9a-f]:/.test(host)) return true; // fe80::/10 link-local
236
+ if (host.startsWith("::ffff:")) return isPrivateIPv4(host.slice("::ffff:".length));
237
+ return false;
238
+ }
239
+ return false;
240
+ }
241
+
242
+ function isPrivateIPv4(host: string): boolean {
243
+ const parts = host.split(".");
244
+ if (parts.length !== 4) return false;
245
+ const nums = parts.map((part) => (/^\d{1,3}$/.test(part) ? Number(part) : Number.NaN));
246
+ if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
247
+ const [a, b] = nums as [number, number, number, number];
248
+ if (a === 0 || a === 10 || a === 127) return true;
249
+ if (a === 169 && b === 254) return true; // link-local, incl. the cloud metadata address
250
+ if (a === 172 && b >= 16 && b <= 31) return true;
251
+ if (a === 192 && b === 168) return true;
252
+ if (a === 192 && b === 0) return true; // 192.0.0.0/24 protocol assignments
253
+ if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
254
+ return a >= 224; // multicast + reserved
255
+ }
256
+
257
+ /**
258
+ * Validate and normalise a sink URL: `http`/`https` only (so `file:`, `gopher:`,
259
+ * `data:` and every other scheme is out), no embedded credentials, and no
260
+ * loopback/private host unless `allowPrivateHosts`. The trailing slash on the
261
+ * path is dropped so `https://ntfy.sh/dpi/` and `https://ntfy.sh/dpi` are one
262
+ * sink and one request URL.
263
+ */
264
+ export function normaliseSinkUrl(raw: string, options: { allowPrivateHosts?: boolean } = {}): string {
265
+ const trimmed = typeof raw === "string" ? raw.trim() : "";
266
+ if (!trimmed) throw invalid("url is required");
267
+ let parsed: URL;
268
+ try {
269
+ parsed = new URL(trimmed);
270
+ } catch {
271
+ throw invalid(`url "${trimmed}" is not a URL`);
272
+ }
273
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
274
+ throw invalid(`url scheme "${parsed.protocol}" is not allowed; use http: or https:`);
275
+ }
276
+ // `new URL("http://user:pw@host")` parses happily; those credentials would be
277
+ // sent on every event and end up in the registry file, so they are refused.
278
+ if (parsed.username || parsed.password) throw invalid("url must not embed credentials (user:password@)");
279
+ if (!parsed.hostname) throw invalid(`url "${trimmed}" has no host`);
280
+ if (!options.allowPrivateHosts && isPrivateHost(parsed.hostname)) {
281
+ throw invalid(
282
+ `url host "${parsed.hostname}" is local/private; pass allowPrivateHosts to reach a LAN sink (e.g. a self-hosted ntfy)`,
283
+ );
284
+ }
285
+ const path = parsed.pathname.replace(/\/+$/, "");
286
+ return `${parsed.origin}${path}${parsed.search}`;
287
+ }
288
+
289
+ /**
290
+ * Does `kind` match the sink's filter? A bare `*`, an exact kind, or a
291
+ * `prefix.*` wildcard (`schedule.*` matches `schedule.ok`). An absent or empty
292
+ * list means the sink wants everything.
293
+ */
294
+ export function matchesEventFilter(patterns: readonly string[], kind: string): boolean {
295
+ if (patterns.length === 0) return true;
296
+ for (const pattern of patterns) {
297
+ if (pattern === "*" || pattern === kind) return true;
298
+ if (pattern.endsWith(".*") && kind.startsWith(pattern.slice(0, -1))) return true;
299
+ }
300
+ return false;
301
+ }
302
+
303
+ /** Strict validation for the write path: a pattern that never matches must be told to whoever typed it. */
304
+ export function normaliseEventPatterns(patterns: readonly string[] | undefined): string[] {
305
+ if (patterns === undefined) return [];
306
+ if (!Array.isArray(patterns)) throw invalid("events must be a list of event kinds");
307
+ const out: string[] = [];
308
+ for (const raw of patterns) {
309
+ if (typeof raw !== "string") throw invalid("events must be strings");
310
+ const pattern = raw.trim();
311
+ if (!pattern) continue; // a trailing comma is not an error worth a 400
312
+ if (pattern.length > MAX_LABEL_LENGTH) throw invalid(`event pattern "${pattern}" is too long`);
313
+ if (!EVENT_PATTERN.test(pattern)) {
314
+ throw invalid(`event pattern "${pattern}" must be an event kind, optionally ending in ".*"`);
315
+ }
316
+ if (out.includes(pattern)) continue;
317
+ out.push(pattern);
318
+ }
319
+ if (out.length > MAX_EVENT_PATTERNS) {
320
+ throw invalid(`${out.length} event patterns; the limit is ${MAX_EVENT_PATTERNS}`);
321
+ }
322
+ return out;
323
+ }
324
+
325
+ /** Lenient variant for the load path: a hand-edited file must not lose its sink over one bad pattern. */
326
+ function coerceEventPatterns(patterns: readonly unknown[]): string[] {
327
+ const out: string[] = [];
328
+ for (const raw of patterns) {
329
+ if (typeof raw !== "string") continue;
330
+ const pattern = raw.trim();
331
+ if (!pattern || !EVENT_PATTERN.test(pattern) || out.includes(pattern)) continue;
332
+ out.push(pattern);
333
+ if (out.length === MAX_EVENT_PATTERNS) break;
334
+ }
335
+ return out;
336
+ }
337
+
338
+ function normaliseLabel(value: string | undefined): string | undefined {
339
+ if (value === undefined) return undefined;
340
+ if (typeof value !== "string") throw invalid("label must be a string");
341
+ const trimmed = value.trim();
342
+ if (!trimmed) return undefined;
343
+ if (trimmed.length > MAX_LABEL_LENGTH) {
344
+ throw invalid(`label is ${trimmed.length} characters; the limit is ${MAX_LABEL_LENGTH}`);
345
+ }
346
+ return trimmed;
347
+ }
348
+
349
+ function normaliseTags(value: readonly string[] | undefined): string[] | undefined {
350
+ if (value === undefined) return undefined;
351
+ if (!Array.isArray(value)) throw invalid("tags must be a list of strings");
352
+ const out: string[] = [];
353
+ for (const raw of value) {
354
+ if (typeof raw !== "string") throw invalid("tags must be strings");
355
+ const tag = raw.trim();
356
+ if (!tag) continue;
357
+ if (tag.length > MAX_TAG_LENGTH) {
358
+ throw invalid(`tag "${tag}" is ${tag.length} characters; the limit is ${MAX_TAG_LENGTH}`);
359
+ }
360
+ if (TAGS_FORBIDDEN.test(tag)) throw invalid(`tag "${tag}" must not contain spaces or commas`);
361
+ if (out.includes(tag)) continue;
362
+ out.push(tag);
363
+ }
364
+ if (out.length > MAX_TAGS) throw invalid(`${out.length} tags; the limit is ${MAX_TAGS}`);
365
+ return out.length > 0 ? out : undefined;
366
+ }
367
+
368
+ /**
369
+ * Validate input against the sink kind. `priority`/`tags` are ntfy's headers, so
370
+ * on a webhook they are a mistake worth reporting rather than a silently
371
+ * dropped field.
372
+ */
373
+ function validateInput(
374
+ input: SinkInput,
375
+ options: { allowPrivateHosts?: boolean },
376
+ ): {
377
+ kind: SinkKind;
378
+ url: string;
379
+ enabled: boolean;
380
+ events: string[];
381
+ label?: string;
382
+ priority?: NotifyPriority;
383
+ tags?: string[];
384
+ } {
385
+ if (!input || typeof input !== "object") throw invalid("sink input is required");
386
+ if (!isKind(input.kind)) throw invalid(`kind must be "webhook" or "ntfy"`);
387
+ const kind = input.kind;
388
+ const url = normaliseSinkUrl(input.url, { allowPrivateHosts: options.allowPrivateHosts === true });
389
+ if (kind === "ntfy") {
390
+ // ntfy publishes to <server>/<topic>; a bare server URL would 404 on every event.
391
+ const path = new URL(url).pathname.replace(/^\/+|\/+$/g, "");
392
+ if (!path) throw invalid(`ntfy url must include the topic: https://ntfy.sh/<topic>`);
393
+ }
394
+ if (input.enabled !== undefined && typeof input.enabled !== "boolean") {
395
+ throw invalid("enabled must be true or false");
396
+ }
397
+ if (input.priority !== undefined && !isPriority(input.priority)) {
398
+ throw invalid(`priority must be one of ${PRIORITIES.join(", ")}`);
399
+ }
400
+ if (input.priority !== undefined && kind !== "ntfy") throw invalid("priority is ntfy-only");
401
+ if (input.tags !== undefined && kind !== "ntfy") throw invalid("tags are ntfy-only");
402
+ const label = normaliseLabel(input.label);
403
+ const priority = input.priority;
404
+ const tags = normaliseTags(input.tags);
405
+ return {
406
+ kind,
407
+ url,
408
+ enabled: input.enabled !== false,
409
+ events: normaliseEventPatterns(input.events),
410
+ ...(label ? { label } : {}),
411
+ ...(priority ? { priority } : {}),
412
+ ...(tags ? { tags } : {}),
413
+ };
414
+ }
415
+
416
+ /**
417
+ * One stored record → a record we can trust. A row with no usable url is dropped
418
+ * (the caller warns) instead of failing the whole file: one hand-edited sink must
419
+ * not cost the operator the others.
420
+ */
421
+ function coerceRecord(raw: unknown, now: number): SinkRecord | undefined {
422
+ if (!raw || typeof raw !== "object") return undefined;
423
+ const source = raw as Record<string, unknown>;
424
+ if (!isKind(source.kind)) return undefined;
425
+ const rawUrl = nonEmptyString(source.url);
426
+ if (!rawUrl) return undefined;
427
+ let url: string;
428
+ try {
429
+ // The file was written by us, so private hosts were already allowed or the
430
+ // operator flipped the flag; re-validating the scheme is what matters here.
431
+ url = normaliseSinkUrl(rawUrl, { allowPrivateHosts: true });
432
+ } catch {
433
+ return undefined;
434
+ }
435
+ const id = nonEmptyString(source.id) ?? newSinkId();
436
+ const label = nonEmptyString(source.label)?.slice(0, MAX_LABEL_LENGTH).trim();
437
+ const tags = Array.isArray(source.tags) ? normaliseTagsLenient(source.tags) : undefined;
438
+ const record: SinkRecord = {
439
+ id,
440
+ kind: source.kind,
441
+ url,
442
+ enabled: source.enabled !== false,
443
+ events: Array.isArray(source.events) ? coerceEventPatterns(source.events) : [],
444
+ createdAt: typeof source.createdAt === "number" ? source.createdAt : now,
445
+ updatedAt: typeof source.updatedAt === "number" ? source.updatedAt : now,
446
+ };
447
+ if (label) record.label = label;
448
+ if (source.kind === "ntfy" && isPriority(source.priority)) record.priority = source.priority;
449
+ if (tags) record.tags = tags;
450
+ if (typeof source.lastDeliveryAt === "number") record.lastDeliveryAt = source.lastDeliveryAt;
451
+ if (typeof source.lastStatus === "number") record.lastStatus = source.lastStatus;
452
+ const lastError = nonEmptyString(source.lastError);
453
+ if (lastError) record.lastError = lastError.slice(0, MAX_ERROR_LENGTH);
454
+ return record;
455
+ }
456
+
457
+ /** Load-path tags: keep what ntfy will accept, drop the rest. */
458
+ function normaliseTagsLenient(tags: readonly unknown[]): string[] | undefined {
459
+ const out: string[] = [];
460
+ for (const raw of tags) {
461
+ if (typeof raw !== "string") continue;
462
+ const tag = raw.trim();
463
+ if (!tag || tag.length > MAX_TAG_LENGTH || TAGS_FORBIDDEN.test(tag)) continue;
464
+ if (out.includes(tag)) continue;
465
+ out.push(tag);
466
+ if (out.length === MAX_TAGS) break;
467
+ }
468
+ return out.length > 0 ? out : undefined;
469
+ }
470
+
471
+ /**
472
+ * Turn whatever is on disk into records. Accepts the current document and a bare
473
+ * sink array (a hand-written `notify.json`); an unknown `version` is refused so a
474
+ * newer build's file is not read as garbage.
475
+ */
476
+ export function migrate(raw: unknown, options: { now?: number } = {}): SinkRecord[] {
477
+ const now = options.now ?? Date.now();
478
+ if (raw === null || raw === undefined) return [];
479
+ const rows = Array.isArray(raw)
480
+ ? raw
481
+ : typeof raw === "object"
482
+ ? (() => {
483
+ const file = raw as Record<string, unknown>;
484
+ const version = file.version;
485
+ if (version !== undefined && version !== null && version !== 0 && version !== 1) {
486
+ throw invalid(`unsupported notify registry version ${String(version)}`);
487
+ }
488
+ const sinks = file.sinks;
489
+ if (sinks === undefined || sinks === null) return [];
490
+ if (!Array.isArray(sinks)) throw invalid("notify registry `sinks` is not a list");
491
+ return sinks;
492
+ })()
493
+ : undefined;
494
+ if (!rows) throw invalid("notify registry file is not a JSON object or a list");
495
+ const out: SinkRecord[] = [];
496
+ for (const entry of rows) {
497
+ const record = coerceRecord(entry, now);
498
+ if (record) out.push(record);
499
+ }
500
+ return out;
501
+ }
502
+
503
+ type ReadResult = { ok: true; records: SinkRecord[] } | { ok: false; missing: boolean; error: unknown };
504
+
505
+ /** Read + migrate one file, folding ENOENT (a fresh device) apart from "unusable". */
506
+ async function readRegistryFile(filePath: string, now: number): Promise<ReadResult> {
507
+ let text: string;
508
+ try {
509
+ text = await readFile(filePath, "utf8");
510
+ } catch (error) {
511
+ const code = (error as NodeJS.ErrnoException).code;
512
+ return { ok: false, missing: code === "ENOENT", error };
513
+ }
514
+ try {
515
+ return { ok: true, records: migrate(JSON.parse(text), { now }) };
516
+ } catch (error) {
517
+ return { ok: false, missing: false, error };
518
+ }
519
+ }
520
+
521
+ /**
522
+ * The sink registry: one JSON file, loaded once at `open`, mutated through an
523
+ * in-memory map that is only committed after the file write lands.
524
+ *
525
+ * Writes are serialised (`run`) so a `create` cannot interleave with a
526
+ * `deliver`'s state write. `deliver` does its network work outside that queue and
527
+ * merges only the delivery state, at most once per call.
528
+ */
529
+ export class NotifySinks {
530
+ /** Absolute path of the main JSON file. */
531
+ readonly filePath: string;
532
+ /** The rolling backup restored by `open` when `filePath` is unusable. */
533
+ readonly backupPath: string;
534
+
535
+ private readonly warn: (message: string, error?: unknown) => void;
536
+ private readonly now: () => number;
537
+ private readonly fetchImpl: FetchLike;
538
+ private readonly cooldownMs: number;
539
+ private readonly timeoutMs: number;
540
+ private readonly allowPrivateHosts: boolean;
541
+ private records = new Map<string, SinkRecord>();
542
+ /** `sinkId` → `eventKind` → when that kind last reserved a delivery slot (orca's cooldown map). */
543
+ private readonly cooldowns = new Map<string, Map<string, number>>();
544
+ /** False until a good file is read or written: while false we must not overwrite `.bak` with junk. */
545
+ private mainIsGood = false;
546
+ private queue: Promise<unknown> = Promise.resolve();
547
+
548
+ private constructor(filePath: string, options: NotifySinksOptions) {
549
+ this.filePath = resolve(filePath);
550
+ this.backupPath = `${this.filePath}.bak`;
551
+ this.warn = options.warn ?? defaultWarn;
552
+ this.now = options.now ?? (() => Date.now());
553
+ this.fetchImpl = options.fetchImpl ?? (globalThis.fetch as unknown as FetchLike);
554
+ this.cooldownMs = options.cooldownMs ?? DEFAULT_COOLDOWN_MS;
555
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
556
+ this.allowPrivateHosts = options.allowPrivateHosts === true;
557
+ }
558
+
559
+ /**
560
+ * Load the registry, or start from an empty one. A missing file is normal (the
561
+ * operator has not configured a sink yet). An unreadable one is moved to
562
+ * `<file>.corrupt-<ts>` and the `.bak` is tried before giving up, because the
563
+ * alternative — carrying on with an empty map over a file we could not parse —
564
+ * loses every sink on the next write.
565
+ */
566
+ static async open(filePath: string, options: NotifySinksOptions = {}): Promise<NotifySinks> {
567
+ const sinks = new NotifySinks(filePath, options);
568
+ await sinks.load();
569
+ return sinks;
570
+ }
571
+
572
+ /** Every configured sink, enabled or not, in creation order. Disabled ones are not delivered to. */
573
+ list(): SinkRecord[] {
574
+ return [...this.records.values()]
575
+ .map(clone)
576
+ .sort((left, right) => left.createdAt - right.createdAt || left.id.localeCompare(right.id));
577
+ }
578
+
579
+ /** One sink by id, or undefined when it does not exist. */
580
+ get(id: string): SinkRecord | undefined {
581
+ const record = this.records.get(id);
582
+ return record ? clone(record) : undefined;
583
+ }
584
+
585
+ /**
586
+ * Add a sink. Validation throws (`NotifySinkError` `invalid`) rather than
587
+ * coercing, so a UI can show the reason: the URL is the one field a typo makes
588
+ * silently useless.
589
+ */
590
+ async create(input: SinkInput): Promise<SinkRecord> {
591
+ const fields = validateInput(input, { allowPrivateHosts: this.allowPrivateHosts });
592
+ return this.run(async () => {
593
+ const staged = new Map(this.records);
594
+ let id = newSinkId();
595
+ while (staged.has(id)) id = newSinkId();
596
+ const now = this.now();
597
+ const record: SinkRecord = { id, ...fields, createdAt: now, updatedAt: now };
598
+ staged.set(record.id, record);
599
+ await this.commit(staged);
600
+ return clone(record);
601
+ });
602
+ }
603
+
604
+ /**
605
+ * Patch a sink. `kind` and `url` are re-validated together, so switching a
606
+ * webhook to ntfy (or pointing it at a LAN host) is judged on the pair that
607
+ * will actually be used. `enabled: false` keeps the record — muting a noisy
608
+ * sink is not the same as forgetting it.
609
+ */
610
+ async update(id: string, patch: Partial<SinkInput> & { enabled?: boolean }): Promise<SinkRecord> {
611
+ return this.run(async () => {
612
+ const staged = new Map(this.records);
613
+ const existing = staged.get(id);
614
+ if (!existing) throw notFound(id);
615
+ const merged: SinkInput = {
616
+ kind: patch.kind ?? existing.kind,
617
+ url: patch.url ?? existing.url,
618
+ enabled: patch.enabled ?? existing.enabled,
619
+ events: "events" in patch ? (patch.events ?? []) : existing.events,
620
+ };
621
+ // `"field" in patch` is what distinguishes "leave it alone" from "clear it".
622
+ if ("label" in patch) merged.label = patch.label;
623
+ else if (existing.label) merged.label = existing.label;
624
+ if ("priority" in patch) merged.priority = patch.priority;
625
+ else if (existing.priority) merged.priority = existing.priority;
626
+ if ("tags" in patch) merged.tags = patch.tags;
627
+ else if (existing.tags) merged.tags = existing.tags;
628
+ const fields = validateInput(merged, { allowPrivateHosts: this.allowPrivateHosts });
629
+ const next: SinkRecord = { ...existing, ...fields, id: existing.id, createdAt: existing.createdAt };
630
+ next.updatedAt = this.now();
631
+ // A field that validation dropped (empty label, no tags) must not linger from the old record.
632
+ if (!fields.label) delete next.label;
633
+ if (!fields.priority) delete next.priority;
634
+ if (!fields.tags) delete next.tags;
635
+ staged.set(next.id, next);
636
+ await this.commit(staged);
637
+ return clone(next);
638
+ });
639
+ }
640
+
641
+ /** Hard delete. Returns false when the id was already gone. */
642
+ async remove(id: string): Promise<boolean> {
643
+ return this.run(async () => {
644
+ if (!this.records.has(id)) return false;
645
+ const staged = new Map(this.records);
646
+ staged.delete(id);
647
+ await this.commit(staged);
648
+ this.cooldowns.delete(id);
649
+ return true;
650
+ });
651
+ }
652
+
653
+ /**
654
+ * Fan one event out to every enabled, matching sink — **sequentially**, in
655
+ * `list()` order, so a slow sink cannot turn a burst into a stampede and the
656
+ * outcome of each attempt is written down before the next one starts.
657
+ *
658
+ * Never throws: a sink that 500s, times out or refuses the connection becomes a
659
+ * `failed` result plus `lastError`/`lastStatus` on its record. The caller is
660
+ * usually a session turn that must not die because someone's webhook did.
661
+ */
662
+ async deliver(event: NotifyEvent, context: { device: string }): Promise<DeliveryResult[]> {
663
+ const device = nonEmptyString(context?.device) ?? "unknown";
664
+ const kind = nonEmptyString(event?.kind);
665
+ if (!kind) {
666
+ // Not a throw: the caller's event was malformed, and no sink should hear about it.
667
+ this.warn("deliver() called without an event kind; nothing was sent");
668
+ return [];
669
+ }
670
+ const normalised: NotifyEvent = {
671
+ kind,
672
+ title: typeof event.title === "string" ? event.title : "",
673
+ body: typeof event.body === "string" ? event.body : "",
674
+ ...(event.data && typeof event.data === "object" ? { data: event.data } : {}),
675
+ };
676
+
677
+ const results: DeliveryResult[] = [];
678
+ const updates = new Map<string, Partial<SinkRecord>>();
679
+ const attempted = this.now();
680
+
681
+ for (const sink of this.list()) {
682
+ if (!sink.enabled) continue;
683
+ if (!matchesEventFilter(sink.events, kind)) {
684
+ results.push({ id: sink.id, kind: sink.kind, status: "skipped", detail: "filtered" });
685
+ continue;
686
+ }
687
+ const silencedUntil = this.reserveCooldown(sink.id, kind, attempted);
688
+ if (silencedUntil !== undefined) {
689
+ results.push({ id: sink.id, kind: sink.kind, status: "skipped", detail: "cooldown" });
690
+ continue;
691
+ }
692
+ results.push(await this.attempt(sink, normalised, device, updates));
693
+ }
694
+
695
+ if (updates.size > 0) await this.commitDeliveryState(updates);
696
+ return results;
697
+ }
698
+
699
+ /**
700
+ * Which sinks are still inside a cooldown window. One entry per configured
701
+ * sink: `silencedUntil` is the epoch-ms end of the longest-running window, and
702
+ * absent when nothing is silenced. Reservations are per (sink, event kind), so
703
+ * a sink can appear here for one kind and still be delivering another.
704
+ */
705
+ recent(): { id: string; silencedUntil?: number }[] {
706
+ const now = this.now();
707
+ return this.list().map((sink) => {
708
+ const kinds = this.cooldowns.get(sink.id);
709
+ let silencedUntil: number | undefined;
710
+ if (kinds) {
711
+ for (const [kind, reservedAt] of kinds) {
712
+ if (now - reservedAt >= this.cooldownMs) {
713
+ kinds.delete(kind);
714
+ continue;
715
+ }
716
+ const until = reservedAt + this.cooldownMs;
717
+ if (silencedUntil === undefined || until > silencedUntil) silencedUntil = until;
718
+ }
719
+ if (kinds.size === 0) this.cooldowns.delete(sink.id);
720
+ }
721
+ return silencedUntil === undefined ? { id: sink.id } : { id: sink.id, silencedUntil };
722
+ });
723
+ }
724
+
725
+ /**
726
+ * Claim this sink's slot for `kind`, or report that it is still cooling down.
727
+ * Reserving *before* the attempt (orca does the same) means a dead endpoint is
728
+ * tried once per window, not once per event.
729
+ */
730
+ private reserveCooldown(id: string, kind: string, now: number): number | undefined {
731
+ const kinds = this.cooldowns.get(id) ?? new Map<string, number>();
732
+ const last = kinds.get(kind);
733
+ if (last !== undefined && now - last < this.cooldownMs) return last + this.cooldownMs;
734
+ kinds.delete(kind);
735
+ kinds.set(kind, now);
736
+ this.cooldowns.set(id, kinds);
737
+ return undefined;
738
+ }
739
+
740
+ /** One sink, one event: build the request, send it, translate the outcome into a result + state patch. */
741
+ private async attempt(
742
+ sink: SinkRecord,
743
+ event: NotifyEvent,
744
+ device: string,
745
+ updates: Map<string, Partial<SinkRecord>>,
746
+ ): Promise<DeliveryResult> {
747
+ const at = this.now();
748
+ const request = sink.kind === "ntfy" ? ntfyRequest(sink, event) : webhookRequest(sink, event, at, device);
749
+ const startedAt = Date.now();
750
+ try {
751
+ const response = await this.fetchImpl(sink.url, {
752
+ method: "POST",
753
+ headers: request.headers,
754
+ body: request.body,
755
+ signal: AbortSignal.timeout(this.timeoutMs),
756
+ });
757
+ const ms = Date.now() - startedAt;
758
+ const status = typeof response?.status === "number" ? response.status : 0;
759
+ if (response?.ok) {
760
+ updates.set(sink.id, { lastDeliveryAt: at, lastStatus: status, lastError: undefined });
761
+ return { id: sink.id, kind: sink.kind, status: "sent", detail: `HTTP ${status}`, ms };
762
+ }
763
+ const detail = `HTTP ${status}`;
764
+ updates.set(sink.id, { lastDeliveryAt: at, lastStatus: status, lastError: detail });
765
+ return { id: sink.id, kind: sink.kind, status: "failed", detail, ms };
766
+ } catch (error) {
767
+ // Includes the AbortSignal.timeout rejection: a hung sink is a failed
768
+ // sink, and the next event in the window will not retry it.
769
+ const ms = Date.now() - startedAt;
770
+ const detail = truncate(describeError(error));
771
+ updates.set(sink.id, { lastDeliveryAt: at, lastError: detail });
772
+ this.warn(`delivery to ${sink.id} (${sink.kind}) failed: ${detail}`, error);
773
+ return { id: sink.id, kind: sink.kind, status: "failed", detail, ms };
774
+ }
775
+ }
776
+
777
+ private async load(): Promise<void> {
778
+ // Same guard as `Store.open`: the data dir holds credentials-adjacent state,
779
+ // so it is created 0700 or tightened before a single byte is written into it.
780
+ ensurePrivateDir(dirname(this.filePath));
781
+ const now = this.now();
782
+
783
+ const main = await readRegistryFile(this.filePath, now);
784
+ if (main.ok) {
785
+ this.adopt(main.records);
786
+ this.mainIsGood = true;
787
+ return;
788
+ }
789
+ if (main.missing) return; // no sinks configured yet: nothing to load, nothing to complain about
790
+
791
+ this.warn(`${this.filePath} is unusable (${describeError(main.error)}); moving it aside`);
792
+ await this.setAside();
793
+
794
+ const backup = await readRegistryFile(this.backupPath, now);
795
+ if (backup.ok) {
796
+ this.adopt(backup.records);
797
+ this.warn(`recovered ${backup.records.length} sink(s) from ${this.backupPath}`);
798
+ return;
799
+ }
800
+ if (!backup.missing) this.warn(`${this.backupPath} is unusable too; starting with no sinks`);
801
+ }
802
+
803
+ /** Rename an unreadable file out of the way instead of deleting it: it is the only copy of that data. */
804
+ private async setAside(): Promise<void> {
805
+ const aside = `${this.filePath}.corrupt-${Date.now()}`;
806
+ try {
807
+ await rename(this.filePath, aside);
808
+ this.warn(`kept the unreadable registry as ${aside}`);
809
+ } catch (error) {
810
+ this.warn(`could not move ${this.filePath} aside; nothing was written over it`, error);
811
+ }
812
+ }
813
+
814
+ private adopt(records: readonly SinkRecord[]): void {
815
+ this.records.clear();
816
+ for (const record of records) this.records.set(record.id, record);
817
+ }
818
+
819
+ /** Stage → persist → swap. A failed write leaves memory exactly as it was. */
820
+ private async commit(staged: Map<string, SinkRecord>): Promise<void> {
821
+ await this.persist([...staged.values()]);
822
+ this.records = staged;
823
+ }
824
+
825
+ /**
826
+ * Delivery state only, merged onto whatever the registry holds *now* — a
827
+ * `create` that landed while the requests were in flight must not be lost by a
828
+ * stale copy of the map.
829
+ */
830
+ private async commitDeliveryState(updates: Map<string, Partial<SinkRecord>>): Promise<void> {
831
+ try {
832
+ await this.run(async () => {
833
+ const staged = new Map(this.records);
834
+ let changed = false;
835
+ for (const [id, patch] of updates) {
836
+ const existing = staged.get(id);
837
+ if (!existing) continue; // removed mid-delivery: nothing to record
838
+ const next: SinkRecord = { ...existing, ...patch };
839
+ if (patch.lastError === undefined) delete next.lastError;
840
+ else next.lastError = truncate(patch.lastError);
841
+ staged.set(id, next);
842
+ changed = true;
843
+ }
844
+ if (changed) await this.commit(staged);
845
+ });
846
+ } catch (error) {
847
+ // `deliver` promised not to throw; the delivery itself already happened.
848
+ this.warn(`could not record delivery state in ${this.filePath}`, error);
849
+ }
850
+ }
851
+
852
+ private run<T>(task: () => Promise<T>): Promise<T> {
853
+ const started = this.queue.then(task, task);
854
+ // Swallow the rejection on the chain only; the caller still sees it.
855
+ this.queue = started.then(
856
+ () => undefined,
857
+ () => undefined,
858
+ );
859
+ return started;
860
+ }
861
+
862
+ /**
863
+ * temp (0600) → rename → chmod, with the previous good file copied to `.bak`
864
+ * first. Rename is atomic within a directory, so a reader sees either the old
865
+ * bytes or the complete new ones — never a torn registry.
866
+ */
867
+ private async persist(records: readonly SinkRecord[]): Promise<void> {
868
+ const dir = dirname(this.filePath);
869
+ ensurePrivateDir(dir); // re-tightened on every write, like the pairing files
870
+ if (this.mainIsGood) await this.backUpMain();
871
+
872
+ const payload = `${JSON.stringify(
873
+ { version: NOTIFY_REGISTRY_VERSION, sinks: [...records] } satisfies NotifyRegistryFile,
874
+ null,
875
+ 2,
876
+ )}\n`;
877
+ const temp = `${this.filePath}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
878
+ try {
879
+ await writeFile(temp, payload, { encoding: "utf8", mode: 0o600 });
880
+ await chmod(temp, 0o600); // umask can only make this stricter, but be explicit
881
+ await rename(temp, this.filePath);
882
+ await chmod(this.filePath, 0o600);
883
+ this.mainIsGood = true;
884
+ } catch (error) {
885
+ await unlink(temp).catch(() => undefined);
886
+ throw error;
887
+ }
888
+ }
889
+
890
+ /** Best effort: a failed backup must not fail the mutation that good file still protects. */
891
+ private async backUpMain(): Promise<void> {
892
+ try {
893
+ await copyFile(this.filePath, this.backupPath);
894
+ await chmod(this.backupPath, 0o600);
895
+ } catch (error) {
896
+ this.warn(`could not refresh ${this.backupPath}`, error);
897
+ }
898
+ }
899
+ }
900
+
901
+ const truncate = (message: string): string =>
902
+ message.length > MAX_ERROR_LENGTH ? `${message.slice(0, MAX_ERROR_LENGTH - 1)}…` : message;
903
+
904
+ /**
905
+ * The webhook wire shape: `{ event, title, body, at, device }` plus the event's
906
+ * `data` merged in at the top level ("delivered as-is"). The five base fields win
907
+ * a collision — a webhook consumer keys on `event`, so `data` cannot rewrite it.
908
+ * `at` is epoch ms, the same clock the registry timestamps use.
909
+ */
910
+ function webhookRequest(
911
+ sink: SinkRecord,
912
+ event: NotifyEvent,
913
+ at: number,
914
+ device: string,
915
+ ): { headers: Record<string, string>; body: string } {
916
+ const payload: Record<string, unknown> = {
917
+ ...(event.data ?? {}),
918
+ event: event.kind,
919
+ title: event.title,
920
+ body: event.body,
921
+ at,
922
+ device,
923
+ };
924
+ return {
925
+ headers: { "content-type": "application/json" },
926
+ body: JSON.stringify(payload),
927
+ };
928
+ }
929
+
930
+ /**
931
+ * ntfy's documented HTTP shape: the message is the raw-ish body and everything
932
+ * else rides in headers — `Title`, `Priority`, `Tags` (comma-joined). The topic
933
+ * is the sink URL's path; the body falls back to the title because ntfy rejects
934
+ * an empty message.
935
+ */
936
+ function ntfyRequest(sink: SinkRecord, event: NotifyEvent): { headers: Record<string, string>; body: string } {
937
+ const headers: Record<string, string> = {
938
+ "content-type": "text/plain; charset=utf-8",
939
+ title: encodeHeader(event.title || sink.label || event.kind),
940
+ };
941
+ if (sink.priority) headers.priority = sink.priority;
942
+ if (sink.tags && sink.tags.length > 0) headers.tags = sink.tags.join(",");
943
+ return { headers, body: event.body.trim() || event.title || event.kind };
944
+ }
945
+
946
+ /** Header values are bytes on the wire: newlines would split the message, so they become spaces. */
947
+ const encodeHeader = (value: string): string => value.replace(/[\r\n]+/g, " ").slice(0, 200);