@betterlu/notiflu 0.0.0-stage → 2.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 betterlu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,636 @@
1
- # Temporary Holding Version
1
+ # @betterlu/notiflu
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Client SDK for [NotifLu](https://github.com/betterlu/notiflu) — async Telegram / Messenger / Discord / LINE / email / ChatLu / web push / NotifLu Android notifications with aliases, retries, inbound replies, and household event routing.
4
+
5
+ Requires Node.js >= 18 at runtime (uses native `fetch`). Zero runtime dependencies. The source test runner uses Node's native TypeScript support and requires Node.js >= 22.15; `npm test` builds `dist/` first.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @betterlu/notiflu
11
+ ```
12
+
13
+ ## Migration from `@betterlu/notif`
14
+
15
+ Version 2.0.0 renames the package from `@betterlu/notif` to `@betterlu/notiflu`. The notification API is unchanged: every export and method from the 1.x SDK is still available, `NotifClient` remains the compatibility export, and `NotifluClient` is the preferred alias. For most consumers the only change is the dependency and import specifier:
16
+
17
+ ```typescript
18
+ import { NotifluClient } from "@betterlu/notiflu";
19
+ ```
20
+
21
+ `NOTIFLU_URL` is the preferred environment variable. `NOTIF_URL` remains as a fallback, and an explicit `baseUrl` option still wins over both. Version 2.1.0 adds the test-runner live-request guard described below. Version 2.2.0 adds optional `threadRootId` on ChatLu typing requests.
22
+
23
+ ## Quick start
24
+
25
+ ```typescript
26
+ import { NotifluClient } from "@betterlu/notiflu";
27
+
28
+ const client = new NotifluClient(); // http://localhost:8778
29
+ // or: new NotifluClient({ baseUrl: process.env.NOTIFLU_URL });
30
+
31
+ const n = await client.send({
32
+ channel: "telegram",
33
+ chatId: "larry",
34
+ message: "Deploy finished",
35
+ });
36
+ console.log(n._id, n.status); // pending — worker delivers async
37
+ ```
38
+
39
+ `baseUrl` is the **origin only** (no `/api`). Defaults to `NOTIFLU_URL`, then legacy `NOTIF_URL`, or `http://localhost:8778`.
40
+
41
+ ```bash
42
+ export NOTIFLU_URL=http://localhost:8778
43
+ ```
44
+
45
+ ### Test-runner guard
46
+
47
+ Under `node:test`, Vitest, Jest, or `NODE_ENV=test`, the SDK refuses non-GET requests to live NotifLu targets before calling `fetch`: loopback on port 8778 or the public `notiflu.70448134.xyz` / `notif.70448134.xyz` hosts. GET reads remain allowed. Point unit tests at a non-live mock origin with injected `fetch`; for intentional live tests, pass `allowLiveRequests: true` or set `NOTIFLU_ALLOW_LIVE=1`.
48
+
49
+ ## Household events
50
+
51
+ NotifLu also routes household events: producers publish a CloudEvents 1.0 JSON envelope with household extensions, subscribers receive at-least-once HTTP deliveries, and consumers can reconcile through a cursor pull.
52
+
53
+ ### Publish with `publish`
54
+
55
+ Use `publish` when the producer needs to know that NotifLu accepted the event. It validates the envelope client-side (including the strict field allowlist and the 64 KiB serialized `data` limit), fills `specversion: "1.0"`, `time`, and `datacontenttype: "application/json"` when omitted, and throws for validation, network, or server failures.
56
+
57
+ ```typescript
58
+ const result = await client.events.publish({
59
+ id: `mail-result:${resultId}`, // recommended idempotency key; NotifLu generates one when absent
60
+ source: "maillu", // /^[a-z0-9][a-z0-9._-]{0,63}$/
61
+ type: "mail.result.upserted", // 2–5 lowercase dot-separated segments
62
+ subject: resultId,
63
+ data: { account: "main", vendor: "market" },
64
+ title: "New parsed purchase", // optional Herald summary, max 160 chars
65
+ urgency: "today", // optional: fyi | today | now
66
+ });
67
+
68
+ console.log(result.events[0]); // { id, seq, duplicate }
69
+ ```
70
+
71
+ A duplicate `(source, id)` returns `duplicate: true` without fanning out again. Pass an array (up to 100 events) to publish a batch. `causedBy` chains an event to its cause: `causationid` becomes `causedBy.id`, and `correlationid` becomes `causedBy.correlationid ?? causedBy.id`.
72
+
73
+ ```typescript
74
+ await client.events.publish(
75
+ {
76
+ source: "agentlu",
77
+ type: "notiflu.inbound.message",
78
+ data: { roomId },
79
+ title: "Misa replied",
80
+ },
81
+ { causedBy: incomingEvent },
82
+ );
83
+ ```
84
+
85
+ ### Best-effort publish with `emit`
86
+
87
+ `emit` accepts the same input but never throws. The returned promise resolves after the event is buffered; publishing continues in the background. Missing event ids are generated once before the first attempt, so retries remain idempotent. Only network/timeout failures and HTTP 408, 425, 429, or 5xx responses are retried three times with backoff; validation failures and other 4xx responses are dropped immediately. The bounded in-memory buffer (about 500 events) drops the oldest pending batch when full and aborts it if it is in flight. At most four background publishes run concurrently by default (`emitConcurrency` on the client). Pass a logger with `warn`/`error` methods per call or on the client to observe those outcomes.
88
+
89
+ ```typescript
90
+ await client.events.emit(
91
+ {
92
+ source: "cartlu",
93
+ type: "shopping.trip.started",
94
+ data: { tripId },
95
+ title: "Shopping trip started",
96
+ },
97
+ { logger: console },
98
+ );
99
+ ```
100
+
101
+ Use `publish` for state changes that must not be lost; use `emit` for best-effort signals where the producer should keep running even when NotifLu is down. Retry timers do not keep a process alive, so short-lived scripts that care about delivery should use `publish`.
102
+
103
+ ### Receive deliveries
104
+
105
+ Subscriptions receive the event envelope (including `seq`) plus headers such as `X-Notiflu-Delivery`, `X-Notiflu-Attempt`, `X-Notiflu-Subscription`, and, when the subscription has a secret, `X-Notiflu-Signature`. `parseEventDelivery` verifies the HMAC with a timing-safe comparison and returns the typed envelope and delivery metadata.
106
+
107
+ Delivery is at-least-once and unordered, so always dedupe on `(source, id)`:
108
+
109
+ ```typescript
110
+ import { createEventDeduper, parseEventDelivery } from "@betterlu/notiflu";
111
+
112
+ const deduper = createEventDeduper({ max: 5000 }); // seen(event) is true for duplicates
113
+
114
+ // Express does not populate req.rawBody automatically; capture it in the JSON parser.
115
+ app.use("/api/events/notiflu", express.json({
116
+ verify: (req, _res, buf) => {
117
+ req.rawBody = buf.toString("utf8");
118
+ },
119
+ }));
120
+
121
+ app.post("/api/events/notiflu", (req, res) => {
122
+ const { event, deliveryId, attempt, subscription } = parseEventDelivery({
123
+ headers: req.headers,
124
+ body: req.body,
125
+ rawBody: req.rawBody,
126
+ secret: process.env.NOTIFLU_EVENT_SECRET,
127
+ });
128
+
129
+ if (deduper.seen(event)) return res.sendStatus(204);
130
+ handleEvent(event);
131
+ res.sendStatus(204);
132
+ });
133
+ ```
134
+
135
+ When `secret` is set, pass the exact bytes as `rawBody` (or pass a raw string/`Uint8Array` as `body`). A parsed object alone is rejected because re-serializing JSON can change key order, escaping, or whitespace and invalidate the HMAC. The helper verifies and parses the same bytes. In a Fetch/Next.js route handler, use `const rawBody = await req.text()` and pass it as `body` or `rawBody`.
136
+
137
+ ### Reconcile with the cursor pull
138
+
139
+ `events.list` returns `{ events, next }` with events ascending by numeric `seq`; `next` is the cursor to pass as `after`, or `null` when no more rows are currently available. Replay from a stored cursor after downtime or a processing bug; the same deduper makes overlap harmless.
140
+
141
+ ```typescript
142
+ let after = await loadCheckpoint();
143
+
144
+ for (;;) {
145
+ const page = await client.events.list({
146
+ after,
147
+ types: ["mail.**", "money.anomaly.detected"],
148
+ limit: 100,
149
+ });
150
+ for (const event of page.events) {
151
+ if (!deduper.seen(event)) await handleEvent(event);
152
+ }
153
+ if (page.next === null || page.events.length === 0) break;
154
+ after = page.next;
155
+ await saveCheckpoint(after);
156
+ }
157
+
158
+ const one = await client.events.get("maillu", "mail-result:abc");
159
+ ```
160
+
161
+ ### Manage event subscriptions and deliveries
162
+
163
+ Dynamic subscriptions use absolute HTTP(S) URLs. Events API resources and request options use camelCase JSON (`maxAttempts`, `startSeq`, `eventSeq`, `createdAt`, and so on).
164
+
165
+ ```typescript
166
+ const sub = await client.events.subscriptions.create({
167
+ name: "herald",
168
+ types: ["mail.**"],
169
+ exclude: ["mail.account.deleted"],
170
+ sources: ["maillu"],
171
+ where: { title: { $exists: true } },
172
+ url: "https://agentlu.example/api/events/notiflu",
173
+ secret: process.env.NOTIFLU_EVENT_SECRET,
174
+ maxAttempts: 10,
175
+ });
176
+
177
+ const { subscriptions: subs } = await client.events.subscriptions.list({ origin: "api" });
178
+ const { deliveries: dead } = await client.events.deliveries.list({ subscription: sub.id, status: "dead" });
179
+ if (dead[0]) await client.events.redrive(dead[0].id); // { redriven: 1, delivery }
180
+ await client.events.redriveSubscription(sub.id, { status: "dead" }); // { redriven: n }
181
+ await client.events.subscriptions.delete(sub.id); // { deleted: true, id }
182
+ const stats = await client.events.stats();
183
+ ```
184
+
185
+ ## Send a notification
186
+
187
+ `send()` enqueues a job (HTTP 202). Status starts as `pending`; the worker delivers it.
188
+
189
+ | Field | Type | Notes |
190
+ |-------|------|--------|
191
+ | `channel` | string | Channel name, provider type (`telegram` \| `messenger` \| `discord` \| `line` \| `email` \| `chatlu` \| `webpush` \| `notiflu`), or ObjectId |
192
+ | `message` | string | Required |
193
+ | `chatId` | string | Alias name first, else raw chat id (webpush: subscription id) |
194
+ | `user` / `userName` | string | Alias-only (back-compat) |
195
+ | `recipient` | `{ chatId?, psid? }` | Raw recipient |
196
+ | `format` | `plain` \| `markdown` \| `html` | Auto-detected if omitted |
197
+ | `idempotencyKey` | string | Optional channel-scoped dedupe key (≤ 200 chars). Replay with the same payload returns the original notification with `deduped: true`; a different payload throws `NotifError` 409. |
198
+ | `wait` | boolean | Wait up to 5s for the send to settle. |
199
+ | `waitMs` | number | Wait 0–15000 ms for the send to settle; `providerMessageId` is filled in on success. |
200
+ | `options` | object | Provider extras (see below) |
201
+
202
+ `chatId` looks up an alias first, then treats the value as a raw id. Discord **webhook** channels may omit `chatId`. Discord bot, LINE, Telegram, Messenger, and ChatLu require it; web push may omit it when `options.person` / `options.app` select registered subscriptions, and notiflu targets person aliases or `options.person`.
203
+
204
+ ```typescript
205
+ // Alias
206
+ await client.send({ channel: "telegram", chatId: "larry", message: "Hello" });
207
+
208
+ // Raw chat id
209
+ await client.send({ channel: "default-telegram", chatId: "123456789", message: "Hello" });
210
+
211
+ // HTML
212
+ await client.send({
213
+ channel: "telegram",
214
+ userName: "larry",
215
+ message: "<b>Alert</b> disk is full",
216
+ format: "html",
217
+ });
218
+
219
+ // Discord webhook (chatId optional)
220
+ await client.send({
221
+ channel: "alerts-discord",
222
+ message: "Build passed",
223
+ options: { username: "ci", avatarUrl: "https://example.com/bot.png" },
224
+ });
225
+
226
+ // Web push to one subscription id
227
+ await client.send({
228
+ channel: "webpush",
229
+ chatId: subscriptionId,
230
+ message: "Need milk",
231
+ options: { title: "cartlu", url: "/" },
232
+ });
233
+
234
+ // Web push to every subscription of a person/app
235
+ await client.send({
236
+ channel: "webpush",
237
+ message: "Need milk",
238
+ options: { title: "cartlu", url: "/", app: "cartlu", person: "larry" },
239
+ });
240
+
241
+ // Shorthand
242
+ await client.notify("Hello", { channel: "telegram", chatId: "larry" });
243
+
244
+ // Wait for the provider id (e.g. a Matrix event_id) — no polling loop
245
+ const chatlu = await client.send({
246
+ channel: "chatlu",
247
+ chatId: "!abcdef:chatlu.lan",
248
+ message: "Thinking…",
249
+ waitMs: 5000,
250
+ });
251
+ if (chatlu.status === "sent") console.log(chatlu.providerMessageId);
252
+
253
+ // Idempotent enqueue: crash-safe retries, one send per key
254
+ const feed = await client.send({
255
+ channel: "chatlu",
256
+ chatId: "!abcdef:chatlu.lan",
257
+ message: "Deploy finished",
258
+ idempotencyKey: `family-feed:${postId}`,
259
+ });
260
+ if (feed.deduped) console.log("already enqueued", feed._id);
261
+ ```
262
+
263
+ ### Options
264
+
265
+ | Key | Providers |
266
+ |-----|-----------|
267
+ | `disableNotification` | Telegram, Discord, LINE (silent) |
268
+ | `protectContent` | Telegram |
269
+ | `linkPreview` | Telegram |
270
+ | `threadId` | Telegram, Discord (webhook path), ChatLu (Matrix thread event id) |
271
+ | `replyToMessageId` | Telegram, ChatLu (Matrix event id) |
272
+ | `replyToEventId` | ChatLu (Matrix event id to reply to) |
273
+ | `threadRootEventId` | ChatLu (Matrix thread root event id) |
274
+ | `editEventId` | ChatLu (Matrix event id to replace with new content) |
275
+ | `extraContent` | ChatLu (object; only `com.agentlu.*` keys are merged into the Matrix content, max 16 KB; also copied into `m.new_content` on edits) |
276
+ | `replyMarkup` | Telegram |
277
+ | `messengerTag` | Messenger (`false` → `RESPONSE`; omit for `MESSAGE_TAG`) |
278
+ | `username` / `avatarUrl` | Discord webhook |
279
+ | `subject` | Email (**required**) |
280
+ | `title` / `url` / `icon` / `badge` | Web push (title defaults to `"Notification"`) |
281
+ | `ttl` | Web push TTL seconds (overrides channel default) |
282
+ | `person` / `app` | Web push target filters (used when `chatId` is omitted) |
283
+ | `tag` | Web push collapse tag |
284
+ | `actions` | Web push action buttons ([{action, title, icon?}] max 2) |
285
+ | `data` | Web push custom JSON payload (max 2 KB) |
286
+ | `requireInteraction` | Web push require interaction (boolean) |
287
+
288
+ ## Status, retry, delete
289
+
290
+ ```typescript
291
+ const items = await client.listNotifications({ status: "failed", limit: 20 });
292
+ const one = await client.getNotification(id);
293
+ await client.retryNotification(id); // failed → pending
294
+ await client.deleteNotification(id);
295
+ ```
296
+
297
+ `listNotifications` filters: `channel` (name or provider type), `status`, `recipient` (regex on chatId/alias), `limit` (default 20, max 50).
298
+
299
+ ## Channels
300
+
301
+ ```typescript
302
+ const channels = await client.listChannels();
303
+ const ch = await client.createChannel({
304
+ name: "alerts-telegram",
305
+ provider: "telegram",
306
+ isDefault: false,
307
+ config: { botToken: "..." },
308
+ });
309
+ await client.updateChannel(ch._id, { isDefault: true });
310
+ await client.registerWebhook(ch._id, { baseUrl: "https://example.com" }); // telegram only
311
+ await client.channels.typing("chatlu", {
312
+ roomId: "!abcdef:chatlu.lan",
313
+ typing: true,
314
+ threadRootId: "$threadRoot:chatlu.lan",
315
+ });
316
+ await client.channels.react("chatlu", {
317
+ roomId: "!abcdef:chatlu.lan",
318
+ eventId: "$event123",
319
+ key: "👀",
320
+ });
321
+ await client.deleteChannel(ch._id);
322
+ ```
323
+
324
+ For ChatLu typing, pass a thread root event ID in `threadRootId` for thread typing or `null` for main-room typing. Omit it for legacy room-scoped behavior.
325
+
326
+ ## ChatLu profiles, rooms, media & DMs
327
+
328
+ Manage the bot's Matrix profile and joined rooms, upload a file and send it as a Matrix message, download media by `mxc`, or resolve a direct room:
329
+
330
+ ```typescript
331
+ // Send — file accepts base64 strings, Uint8Array or ArrayBuffer
332
+ const sent = await client.channelMedia("default-chatlu", {
333
+ roomId: "!abcdef:chatlu.lan",
334
+ file: await readFile("cat.png"),
335
+ filename: "cat.png",
336
+ mimetype: "image/png",
337
+ caption: "Look at this", // optional; becomes the event body
338
+ replyToEventId: "$previous", // optional
339
+ threadRootEventId: "$root", // optional
340
+ extraContent: { // optional; only com.agentlu.* is merged
341
+ "com.agentlu.doc": { version: 1, title: "Weekly plan" },
342
+ },
343
+ });
344
+ // sent: { eventId, mxc, roomId, msgtype }
345
+
346
+ // Download (mxc URIs arrive in inbound `media.mxc`)
347
+ const media = await client.channelMediaDownload("default-chatlu", "mxc://chatlu.lan/AbCdEf");
348
+ // media: { contentType, bytes: ArrayBuffer, filename? }
349
+
350
+ // Find or create the bot's DM with a user
351
+ const dm = await client.channelDirectRoom("default-chatlu", "@misa:chatlu.lan");
352
+ // dm: { roomId, created }
353
+
354
+ const profile = await client.channelProfile("agentlu-bot-meal-coach");
355
+ await client.setChannelProfile("agentlu-bot-meal-coach", {
356
+ displayName: "Meal Coach",
357
+ avatar: { base64: imageBase64, mimetype: "image/png", filename: "avatar.png" },
358
+ });
359
+ // An existing Matrix media URI can be used without re-uploading:
360
+ await client.setChannelProfile("agentlu-bot-meal-coach", {
361
+ avatar: { mxc: "mxc://chatlu.lan/AbCdEf" },
362
+ });
363
+
364
+ const rooms = await client.channelRooms("agentlu-bot-meal-coach");
365
+ await client.channelLeave("agentlu-bot-meal-coach", rooms[0].roomId);
366
+
367
+ // Create a private, unencrypted group room from the bot account.
368
+ // Include every bot that will join in `invite` (Synapse requires an invite
369
+ // before the join endpoint can add a bot to a private room).
370
+ const created = await client.channelCreateRoom("agentlu-bot-cradle", {
371
+ name: "Dinner planning",
372
+ invite: ["@larry:chatlu.lan", "@agentlu-bot-meal-coach:chatlu.lan"],
373
+ });
374
+ // created: { roomId, name }
375
+
376
+ // Each invited agent bot joins by room ID; already joined is a no-op success.
377
+ await client.channelJoin("agentlu-bot-meal-coach", created.roomId);
378
+ // { joined: true, roomId }
379
+ ```
380
+
381
+ - `msgtype` auto-detects from `mimetype`: `image/*` → `m.image`, `audio/*` → `m.audio`, `video/*` → `m.video`, else `m.file`. Explicit `msgtype` must be one of those four.
382
+ - `caption` becomes `content.body` and `filename` stays in `info.filename` (Matrix/MSC2530). `info` includes `mimetype`, `size`, and `w`/`h` for PNG/GIF/JPEG.
383
+ - `file` is limited to **25 MB decoded**. Media sends are **direct** (not queued) and return `{ eventId, mxc, roomId, msgtype }`; errors keep upstream Matrix statuses (`400` invalid payload, `413` too large, `404` media not found).
384
+ - `channelMediaDownload` returns `{ contentType, bytes: ArrayBuffer, filename? }`; the bot token stays on the NotifLu server.
385
+ - `channelDirectRoom` returns `{ roomId, created }`; `created: false` means an existing joined room from `m.direct` was reused.
386
+ - `channelProfile` / `setChannelProfile` return `{ userId, displayName, avatarUrl }`; absent profile fields are `null`. Display names are limited to 1–100 characters. Avatar uploads must use `image/*` and are limited to 25 MB decoded (40 MB JSON body); an existing `mxc://` URI may be supplied instead.
387
+ - `channelRooms` returns up to 200 `{ roomId, name, isDirect, memberCount }` entries. A room without a name has `name: null`. `channelLeave` returns `{ left: true }` after leaving and forgetting the room.
388
+ - `channelRoomMessages(name, roomId, { limit? })` returns `{ roomId, events }` newest first (default 30, max 100). Events include `providerEventId`, `sender`, `text`, `msgtype`, `media`, `transcript`, `replyTo`, `threadRootId`, and `timestamp`. Matrix history visibility applies, so only events the bot may see are returned.
389
+ - `channelCreateRoom(name, { name, invite? })` creates a private, unencrypted group room (`preset: private_chat`, `is_direct: false`) and returns `{ roomId, name }`. `name` is 1–100 characters; `invite` accepts up to 50 Matrix user IDs, is deduplicated, and ignores the channel bot's own MXID. Agent bots that should join must be in `invite`. Nothing is recorded in `m.direct`. A `200` createRoom response without a `room_id` returns a non-retryable `502` to avoid creating duplicate rooms.
390
+ - `channelJoin(name, roomId)` joins an existing room and returns `{ joined: true, roomId }`. Already-joined rooms succeed without another Matrix join. Permanent Matrix errors keep their upstream status; 429/5xx/network errors return a retryable `503`.
391
+
392
+ Secrets in responses are masked (`abcd••••wxyz`).
393
+
394
+ ### Channel config by provider
395
+
396
+ | Provider | Required | Optional |
397
+ |----------|----------|----------|
398
+ | `telegram` | `botToken` | `webhookSecretToken` |
399
+ | `messenger` | `pageAccessToken` | `apiVersion`, `verifyToken`, `appSecret` |
400
+ | `discord` | `webhookUrl` and/or `botToken` | `username` |
401
+ | `line` | `channelAccessToken` | `channelSecret` |
402
+ | `email` | `host`, `user`, `pass` | `port` (587), `secure` (false), `from`, `fromName` |
403
+ | `chatlu` | `homeserverUrl`, `accessToken` | `inbound` (boolean), `forwardReactions` (boolean, default `false`), `allowedInviters` (string[]) |
404
+ | `webpush` | — | `vapidSubject`, `vapidPublicKey`, `vapidPrivateKey`, `ttl` (fallback: `WEBPUSH_VAPID_*` env) |
405
+
406
+ Name: `^[a-zA-Z0-9_-]+$`, not reserved (`telegram` / `messenger` / `discord` / `line` / `email` / `chatlu` / `webpush` / `notiflu`).
407
+
408
+ Email channels send over SMTP and require `options.subject`; `chatId` is the recipient address (alias lookup applies first).
409
+
410
+ ChatLu channels deliver to Matrix rooms via the homeserver's client API; `chatId` is a room ID (`!room:chatlu.lan`) or room alias (`#room:chatlu.lan`). When `inbound: true`, an in-process worker syncs incoming messages. `forwardReactions: true` additionally forwards annotation reactions; it defaults to false and skips bot-authored reactions, initial history, and reaction redactions. Reaction delivery is strictly opt-in per subscriber: `events` must explicitly include `m.reaction`; missing/empty filters are excluded. Create the bot with `scripts/chatlu-bot-setup.sh`.
411
+
412
+ Household family-room updates: don’t post into the family room directly from apps through NotifLu; raise a household signal (`POST /v1/household/signals` / `@betterlu/agentlu` `household.signal()`). Herald decides what/when to post and delivers through NotifLu. See AgentLu `docs/household-signals.md`.
413
+
414
+ ## Web push subscriptions
415
+
416
+ Apps register their browser push subscriptions so NotifLu can deliver `webpush` notifications (no `web-push` dependency needed in the app). Keyed by `endpoint`; `person` defaults to `agent`.
417
+
418
+ ```typescript
419
+ await client.registerPushSubscription({
420
+ app: "cartlu",
421
+ person: "larry",
422
+ endpoint: sub.endpoint,
423
+ keys: { p256dh: sub.keys.p256dh, auth: sub.keys.auth },
424
+ });
425
+
426
+ const subs = await client.listPushSubscriptions({ app: "cartlu", person: "larry" });
427
+ const one = await client.listPushSubscriptions({ endpoint: sub.endpoint });
428
+ await client.deletePushSubscription({ id: subs[0]._id }); // or { endpoint }
429
+ ```
430
+
431
+ Expired endpoints (404/410 from the push service) are dropped automatically at delivery time. Web push channels need VAPID config: on the channel (`vapidSubject` / `vapidPublicKey` / `vapidPrivateKey` / `ttl`) or `WEBPUSH_VAPID_SUBJECT` / `WEBPUSH_VAPID_PUBLIC_KEY` / `WEBPUSH_VAPID_PRIVATE_KEY` / `WEBPUSH_TTL` env.
432
+
433
+ ## Aliases
434
+
435
+ Friendly name → per-channel chat ids.
436
+
437
+ ```typescript
438
+ await client.createAlias({
439
+ name: "larry",
440
+ mappings: { "default-telegram": "123456789", "alerts-discord": "987654321" },
441
+ });
442
+ const aliases = await client.listAliases();
443
+ const people = await client.listAliases({ person: true });
444
+ const misa = await client.listAliases({ name: "misa" });
445
+ await client.updateAlias(id, { mappings: { "default-telegram": "111" } });
446
+ await client.deleteAlias(id);
447
+ ```
448
+
449
+ ## Inbound & Subscriptions
450
+
451
+ Telegram / Messenger / LINE webhooks and ChatLu Matrix sync worker capture inbound messages and fan out to registered webhook subscriptions.
452
+
453
+ ### Inbound responses (history)
454
+
455
+ ```typescript
456
+ const replies = await client.listInbound({ channel: "telegram", matched: true, limit: 20 });
457
+ const full = await client.getInbound(replies[0]._id);
458
+ ```
459
+
460
+ Matrix media messages carry `msgtype` and a normalized `media` field (`{ mxc, mimetype, size, filename, duration? }`), both in stored inbound responses and in the webhook fanout payload:
461
+
462
+ ```typescript
463
+ const media = replies.find((r) => r.media)?.media;
464
+ if (media) {
465
+ const bytes = await client.channelMediaDownload("default-chatlu", media.mxc);
466
+ }
467
+ ```
468
+
469
+ ChatLu reply/thread events also expose `replyTo`, `replyToSender` (MXID of the replied-to event sender), `threadRoot` / `threadRootId`, and `threadRootSender` in both the stored response and `NormalizedInboundEvent`. Sender fields are omitted when NotifLu cannot resolve them.
470
+
471
+ When `forwardReactions: true`, reaction webhook payloads add `kind: "reaction"`, `reaction: { "key": "👍", "targetEventId": "$herald-post" }`, `eventId`, and `timestamp` (Matrix milliseconds). Reaction-only `senderDisplayName` is included when available. The shared envelope retains `roomId`, `sender`, `isDirect`, and ISO `receivedAt`.
472
+
473
+ ### Inbound subscriptions (webhook fanout)
474
+
475
+ Register endpoints to receive normalized inbound messages with HMAC-SHA256 signature verification:
476
+
477
+ ```typescript
478
+ const sub = await client.inbound.subscribe({
479
+ channel: "chatlu",
480
+ url: "http://localhost:8799/webhook/chatlu",
481
+ secret: process.env.CHATLU_WEBHOOK_SECRET,
482
+ });
483
+
484
+ const subs = await client.inbound.list({ channel: "chatlu" });
485
+ const deliveries = await client.inbound.listDeliveries({ subscriptionId: sub._id, status: "failed" });
486
+ await client.inbound.unsubscribe(sub._id);
487
+ ```
488
+
489
+ To receive both messages and reactions, explicitly list both Matrix event types; an unfiltered subscription does not receive reactions:
490
+
491
+ ```typescript
492
+ await client.inbound.subscribe({
493
+ channel: "chatlu",
494
+ url: "http://localhost:8799/webhook/chatlu",
495
+ secret: process.env.CHATLU_WEBHOOK_SECRET,
496
+ events: ["m.room.message", "m.reaction"],
497
+ });
498
+ ```
499
+
500
+ Verify signature in receiving webhook handlers:
501
+
502
+ ```typescript
503
+ import { verifySignature } from "@betterlu/notiflu";
504
+
505
+ const isValid = verifySignature(rawBody, req.headers["x-notif-signature"], secret);
506
+ ```
507
+
508
+ ## Health
509
+
510
+ ```typescript
511
+ const h = await client.health();
512
+ // { ok, workerRunning, notificationCount, aliasCount, channelCount, channels, providers, chatluSync? }
513
+ // chatluSync = { running, loops: [{ channelId, channel, active, botUserId, tokenStatus, lastSyncAt, lastErrorAt, lastErrorCode }] }
514
+ // Informational only: a rejected ChatLu token never flips `ok`.
515
+ ```
516
+
517
+ ## Errors
518
+
519
+ ```typescript
520
+ import { NotifError } from "@betterlu/notiflu";
521
+
522
+ try {
523
+ await client.send({ channel: "telegram", message: "" });
524
+ } catch (err) {
525
+ if (err instanceof NotifError) {
526
+ console.error(err.status, err.message); // 400 message is required
527
+ // Events API errors may also expose err.code and err.details,
528
+ // for example "hop_limit" or "schema_invalid".
529
+ } else {
530
+ throw err;
531
+ }
532
+ }
533
+ ```
534
+
535
+ No auth. Inject `fetch` for tests or custom middleware. In a test runner, use a non-live mock origin unless the test intentionally allows live requests:
536
+
537
+ ```typescript
538
+ const client = new NotifluClient({
539
+ baseUrl: "http://notiflu.test",
540
+ fetch: myFetch,
541
+ });
542
+ ```
543
+
544
+ ## API reference
545
+
546
+ ### `NotifluClient` / `NotifClient`
547
+
548
+ | Method | Returns | Description |
549
+ |--------|---------|-------------|
550
+ | `health()` | `HealthResponse` | Worker + channel list |
551
+ | `events.publish(input, opts?)` | `PublishEventsResult` | Validate and publish one event or a batch; throws on failure |
552
+ | `events.emit(input, opts?)` | `Promise<void>` | Best-effort buffered publish with three background retries; never throws |
553
+ | `events.list(query?)` | `ListEventsResult` | Cursor page ascending by `seq` |
554
+ | `events.get(source, id)` | `NotifluEvent` | Read one event |
555
+ | `events.subscriptions.list(query?)` | `ListEventSubscriptionsResult` | List event subscriptions as `{ subscriptions }` |
556
+ | `events.subscriptions.create(req)` | `EventSubscription` | Create an API-origin event subscription |
557
+ | `events.subscriptions.delete(id)` | `DeleteEventSubscriptionResult` | Delete an API-origin subscription (`{ deleted: true, id }`) |
558
+ | `events.deliveries.list(query?)` | `ListEventDeliveriesResult` | List event deliveries as `{ deliveries }` |
559
+ | `events.redrive(deliveryId)` | `RedriveEventDeliveryResult` | Redrive one dead delivery |
560
+ | `events.redriveSubscription(id, { status? })` | `RedriveEventSubscriptionResult` | Redrive matching deliveries for a subscription |
561
+ | `events.stats()` | `EventStats` | Event lane counters |
562
+ | `send(req)` | `Notification` | Enqueue (202, or 200 when settled / deduped) |
563
+ | `notify(message, opts?)` | `Notification` | Shorthand for `send` |
564
+ | `notifyTelegramHtml(user, html)` | `Notification` | Telegram HTML to an alias (`userName`) |
565
+ | `escapeHtml(value)` | `string` | Escape `& < > " '` for Telegram HTML |
566
+ | `listNotifications(query?)` | `Notification[]` | Filter queue |
567
+ | `getNotification(id)` | `Notification` | One notification |
568
+ | `retryNotification(id)` | `Notification` | Re-queue a failed send |
569
+ | `deleteNotification(id)` | `Notification` | Delete |
570
+ | `listChannels()` | `Channel[]` | All channels |
571
+ | `getChannel(id)` | `Channel` | One channel (secrets masked) |
572
+ | `createChannel(req)` | `Channel` | Create |
573
+ | `updateChannel(id, req)` | `Channel` | Partial update |
574
+ | `deleteChannel(id)` | `Channel` | Delete |
575
+ | `registerWebhook(id, req?)` | `RegisterWebhookResult` | Telegram `setWebhook` |
576
+ | `channels.typing(name, req)` | `ChannelTypingResult` | Send typing indicator |
577
+ | `channels.react(name, req)` | `ChannelReactionResult` | Send an emoji reaction (`m.annotation`) |
578
+ | `channelMedia(name, req)` / `channels.media(name, req)` | `ChannelMediaResult` | Upload + send a Matrix media message (direct) |
579
+ | `channelMediaDownload(name, mxc)` / `channels.downloadMedia(name, mxc)` | `ChannelMediaDownloadResult` | Download media bytes by `mxc` |
580
+ | `channelDirectRoom(name, userId)` / `channels.directRoom(name, userId)` | `ChannelDirectRoomResult` | Find or create a DM |
581
+ | `channelProfile(name)` | `ChannelProfile` | Get the bot's Matrix profile |
582
+ | `setChannelProfile(name, req)` | `ChannelProfile` | Update display name and/or avatar |
583
+ | `channelRooms(name)` | `ChannelRoom[]` | List joined rooms (up to 200) |
584
+ | `channelRoomMessages(name, roomId, { limit? })` | `ChannelRoomMessages` | Read recent room messages as the bot (newest first) |
585
+ | `channelCreateRoom(name, req)` | `ChannelCreatedRoom` | Create a private, unencrypted group room |
586
+ | `channelJoin(name, roomId)` | `ChannelJoinResult` | Join a room by ID (idempotent) |
587
+ | `channelLeave(name, roomId)` | `ChannelLeaveResult` | Leave and forget a room |
588
+ | `registerPushSubscription(req)` | `PushSubscription` | Upsert a web push subscription by endpoint |
589
+ | `listPushSubscriptions(query?)` | `PushSubscription[]` | Filter by `person`, `app`, `endpoint`, `limit` |
590
+ | `deletePushSubscription({ id?, endpoint? })` | `PushSubscription` | Delete a subscription |
591
+ | `listAliases(query?)` | `Alias[]` | Filter by `person`, `name`, `limit` |
592
+ | `getAlias(id)` | `Alias` | One alias |
593
+ | `createAlias(req)` | `Alias` | Create |
594
+ | `updateAlias(id, req)` | `Alias` | Update |
595
+ | `deleteAlias(id)` | `Alias` | Delete |
596
+ | `listInbound(query?)` | `InboundResponse[]` | Inbound events (no `rawPayload`) |
597
+ | `getInbound(id)` | `InboundResponse` | One inbound (includes `rawPayload`) |
598
+ | `inbound.subscribe(req)` | `InboundSubscription` | Register inbound webhook |
599
+ | `inbound.list(query?)` | `InboundSubscription[]` | List inbound subscriptions |
600
+ | `inbound.unsubscribe(id)` | `InboundSubscription` | Delete inbound subscription |
601
+ | `inbound.listDeliveries(query?)` | `InboundDelivery[]` | List delivery status and history |
602
+ | `app.people()` | `AppPerson[]` | List Larry/Misa and 30-day feed counts |
603
+ | `app.registerDevice(req)` / `app.unregisterDevice(installationId)` | `AppDevice` | Register or remove an Android installation |
604
+ | `app.feed(query)` | `AppFeedPage` | Read correlated, cursor-paginated NotifLu items |
605
+ | `app.detail(id, person)` | `AppNotificationDetail` | Read full message, device engagement, and replies |
606
+ | `app.markRead(id, person)` / `app.readAll(person, before?)` | read result | Update per-person read state |
607
+ | `app.event(id, req)` | `AppEventResult` | Record delivery/open/dismiss/action (actions fan out to inbound subscriptions) |
608
+ | `app.sources(person)` | `AppSourceSummary[]` | Seven-day source summary |
609
+ | `app.testPush(installationId)` | `AppTestPushResult` | Queue one-device FCM test |
610
+
611
+ ### Standalone exports
612
+
613
+ - `verifySignature(rawBody, signatureHeader, secret): boolean`
614
+ - `parseEventDelivery({ headers, body?, rawBody?, secret? }): ParsedEventDelivery`
615
+ - `createEventDeduper({ max? }): EventDeduper` — `seen(event)` is `true` for duplicate `(source, id)` keys
616
+ - `NotifClient` is the 1.x compatibility export; `NotifluClient` is the preferred alias
617
+
618
+ ### NotifLu example
619
+
620
+ ```typescript
621
+ await client.app.registerDevice({
622
+ installationId: "android-install-1",
623
+ person: "larry",
624
+ fcmToken,
625
+ deviceName: "Pixel",
626
+ });
627
+
628
+ const feed = await client.app.feed({ person: "larry", scope: "mine", limit: 30 });
629
+ if (feed.items[0]) await client.app.markRead(feed.items[0].id, "larry");
630
+ ```
631
+
632
+ `FCM_SERVICE_ACCOUNT_JSON` configures the server-side `notiflu` provider. Device registration responses never return FCM tokens.
633
+
634
+ ## License
635
+
636
+ MIT