@betterlu/notiflu 0.0.0-stage → 2.0.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,626 @@
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.
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
+ ## Household events
46
+
47
+ 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.
48
+
49
+ ### Publish with `publish`
50
+
51
+ 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.
52
+
53
+ ```typescript
54
+ const result = await client.events.publish({
55
+ id: `mail-result:${resultId}`, // recommended idempotency key; NotifLu generates one when absent
56
+ source: "maillu", // /^[a-z0-9][a-z0-9._-]{0,63}$/
57
+ type: "mail.result.upserted", // 2–5 lowercase dot-separated segments
58
+ subject: resultId,
59
+ data: { account: "main", vendor: "market" },
60
+ title: "New parsed purchase", // optional Herald summary, max 160 chars
61
+ urgency: "today", // optional: fyi | today | now
62
+ });
63
+
64
+ console.log(result.events[0]); // { id, seq, duplicate }
65
+ ```
66
+
67
+ 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`.
68
+
69
+ ```typescript
70
+ await client.events.publish(
71
+ {
72
+ source: "agentlu",
73
+ type: "notiflu.inbound.message",
74
+ data: { roomId },
75
+ title: "Misa replied",
76
+ },
77
+ { causedBy: incomingEvent },
78
+ );
79
+ ```
80
+
81
+ ### Best-effort publish with `emit`
82
+
83
+ `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.
84
+
85
+ ```typescript
86
+ await client.events.emit(
87
+ {
88
+ source: "cartlu",
89
+ type: "shopping.trip.started",
90
+ data: { tripId },
91
+ title: "Shopping trip started",
92
+ },
93
+ { logger: console },
94
+ );
95
+ ```
96
+
97
+ 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`.
98
+
99
+ ### Receive deliveries
100
+
101
+ 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.
102
+
103
+ Delivery is at-least-once and unordered, so always dedupe on `(source, id)`:
104
+
105
+ ```typescript
106
+ import { createEventDeduper, parseEventDelivery } from "@betterlu/notiflu";
107
+
108
+ const deduper = createEventDeduper({ max: 5000 }); // seen(event) is true for duplicates
109
+
110
+ // Express does not populate req.rawBody automatically; capture it in the JSON parser.
111
+ app.use("/api/events/notiflu", express.json({
112
+ verify: (req, _res, buf) => {
113
+ req.rawBody = buf.toString("utf8");
114
+ },
115
+ }));
116
+
117
+ app.post("/api/events/notiflu", (req, res) => {
118
+ const { event, deliveryId, attempt, subscription } = parseEventDelivery({
119
+ headers: req.headers,
120
+ body: req.body,
121
+ rawBody: req.rawBody,
122
+ secret: process.env.NOTIFLU_EVENT_SECRET,
123
+ });
124
+
125
+ if (deduper.seen(event)) return res.sendStatus(204);
126
+ handleEvent(event);
127
+ res.sendStatus(204);
128
+ });
129
+ ```
130
+
131
+ 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`.
132
+
133
+ ### Reconcile with the cursor pull
134
+
135
+ `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.
136
+
137
+ ```typescript
138
+ let after = await loadCheckpoint();
139
+
140
+ for (;;) {
141
+ const page = await client.events.list({
142
+ after,
143
+ types: ["mail.**", "money.anomaly.detected"],
144
+ limit: 100,
145
+ });
146
+ for (const event of page.events) {
147
+ if (!deduper.seen(event)) await handleEvent(event);
148
+ }
149
+ if (page.next === null || page.events.length === 0) break;
150
+ after = page.next;
151
+ await saveCheckpoint(after);
152
+ }
153
+
154
+ const one = await client.events.get("maillu", "mail-result:abc");
155
+ ```
156
+
157
+ ### Manage event subscriptions and deliveries
158
+
159
+ Dynamic subscriptions use absolute HTTP(S) URLs. Events API resources and request options use camelCase JSON (`maxAttempts`, `startSeq`, `eventSeq`, `createdAt`, and so on).
160
+
161
+ ```typescript
162
+ const sub = await client.events.subscriptions.create({
163
+ name: "herald",
164
+ types: ["mail.**"],
165
+ exclude: ["mail.account.deleted"],
166
+ sources: ["maillu"],
167
+ where: { title: { $exists: true } },
168
+ url: "https://agentlu.example/api/events/notiflu",
169
+ secret: process.env.NOTIFLU_EVENT_SECRET,
170
+ maxAttempts: 10,
171
+ });
172
+
173
+ const { subscriptions: subs } = await client.events.subscriptions.list({ origin: "api" });
174
+ const { deliveries: dead } = await client.events.deliveries.list({ subscription: sub.id, status: "dead" });
175
+ if (dead[0]) await client.events.redrive(dead[0].id); // { redriven: 1, delivery }
176
+ await client.events.redriveSubscription(sub.id, { status: "dead" }); // { redriven: n }
177
+ await client.events.subscriptions.delete(sub.id); // { deleted: true, id }
178
+ const stats = await client.events.stats();
179
+ ```
180
+
181
+ ## Send a notification
182
+
183
+ `send()` enqueues a job (HTTP 202). Status starts as `pending`; the worker delivers it.
184
+
185
+ | Field | Type | Notes |
186
+ |-------|------|--------|
187
+ | `channel` | string | Channel name, provider type (`telegram` \| `messenger` \| `discord` \| `line` \| `email` \| `chatlu` \| `webpush` \| `notiflu`), or ObjectId |
188
+ | `message` | string | Required |
189
+ | `chatId` | string | Alias name first, else raw chat id (webpush: subscription id) |
190
+ | `user` / `userName` | string | Alias-only (back-compat) |
191
+ | `recipient` | `{ chatId?, psid? }` | Raw recipient |
192
+ | `format` | `plain` \| `markdown` \| `html` | Auto-detected if omitted |
193
+ | `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. |
194
+ | `wait` | boolean | Wait up to 5s for the send to settle. |
195
+ | `waitMs` | number | Wait 0–15000 ms for the send to settle; `providerMessageId` is filled in on success. |
196
+ | `options` | object | Provider extras (see below) |
197
+
198
+ `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`.
199
+
200
+ ```typescript
201
+ // Alias
202
+ await client.send({ channel: "telegram", chatId: "larry", message: "Hello" });
203
+
204
+ // Raw chat id
205
+ await client.send({ channel: "default-telegram", chatId: "123456789", message: "Hello" });
206
+
207
+ // HTML
208
+ await client.send({
209
+ channel: "telegram",
210
+ userName: "larry",
211
+ message: "<b>Alert</b> disk is full",
212
+ format: "html",
213
+ });
214
+
215
+ // Discord webhook (chatId optional)
216
+ await client.send({
217
+ channel: "alerts-discord",
218
+ message: "Build passed",
219
+ options: { username: "ci", avatarUrl: "https://example.com/bot.png" },
220
+ });
221
+
222
+ // Web push to one subscription id
223
+ await client.send({
224
+ channel: "webpush",
225
+ chatId: subscriptionId,
226
+ message: "Need milk",
227
+ options: { title: "cartlu", url: "/" },
228
+ });
229
+
230
+ // Web push to every subscription of a person/app
231
+ await client.send({
232
+ channel: "webpush",
233
+ message: "Need milk",
234
+ options: { title: "cartlu", url: "/", app: "cartlu", person: "larry" },
235
+ });
236
+
237
+ // Shorthand
238
+ await client.notify("Hello", { channel: "telegram", chatId: "larry" });
239
+
240
+ // Wait for the provider id (e.g. a Matrix event_id) — no polling loop
241
+ const chatlu = await client.send({
242
+ channel: "chatlu",
243
+ chatId: "!abcdef:chatlu.lan",
244
+ message: "Thinking…",
245
+ waitMs: 5000,
246
+ });
247
+ if (chatlu.status === "sent") console.log(chatlu.providerMessageId);
248
+
249
+ // Idempotent enqueue: crash-safe retries, one send per key
250
+ const feed = await client.send({
251
+ channel: "chatlu",
252
+ chatId: "!abcdef:chatlu.lan",
253
+ message: "Deploy finished",
254
+ idempotencyKey: `family-feed:${postId}`,
255
+ });
256
+ if (feed.deduped) console.log("already enqueued", feed._id);
257
+ ```
258
+
259
+ ### Options
260
+
261
+ | Key | Providers |
262
+ |-----|-----------|
263
+ | `disableNotification` | Telegram, Discord, LINE (silent) |
264
+ | `protectContent` | Telegram |
265
+ | `linkPreview` | Telegram |
266
+ | `threadId` | Telegram, Discord (webhook path), ChatLu (Matrix thread event id) |
267
+ | `replyToMessageId` | Telegram, ChatLu (Matrix event id) |
268
+ | `replyToEventId` | ChatLu (Matrix event id to reply to) |
269
+ | `threadRootEventId` | ChatLu (Matrix thread root event id) |
270
+ | `editEventId` | ChatLu (Matrix event id to replace with new content) |
271
+ | `extraContent` | ChatLu (object; only `com.agentlu.*` keys are merged into the Matrix content, max 16 KB; also copied into `m.new_content` on edits) |
272
+ | `replyMarkup` | Telegram |
273
+ | `messengerTag` | Messenger (`false` → `RESPONSE`; omit for `MESSAGE_TAG`) |
274
+ | `username` / `avatarUrl` | Discord webhook |
275
+ | `subject` | Email (**required**) |
276
+ | `title` / `url` / `icon` / `badge` | Web push (title defaults to `"Notification"`) |
277
+ | `ttl` | Web push TTL seconds (overrides channel default) |
278
+ | `person` / `app` | Web push target filters (used when `chatId` is omitted) |
279
+ | `tag` | Web push collapse tag |
280
+ | `actions` | Web push action buttons ([{action, title, icon?}] max 2) |
281
+ | `data` | Web push custom JSON payload (max 2 KB) |
282
+ | `requireInteraction` | Web push require interaction (boolean) |
283
+
284
+ ## Status, retry, delete
285
+
286
+ ```typescript
287
+ const items = await client.listNotifications({ status: "failed", limit: 20 });
288
+ const one = await client.getNotification(id);
289
+ await client.retryNotification(id); // failed → pending
290
+ await client.deleteNotification(id);
291
+ ```
292
+
293
+ `listNotifications` filters: `channel` (name or provider type), `status`, `recipient` (regex on chatId/alias), `limit` (default 20, max 50).
294
+
295
+ ## Channels
296
+
297
+ ```typescript
298
+ const channels = await client.listChannels();
299
+ const ch = await client.createChannel({
300
+ name: "alerts-telegram",
301
+ provider: "telegram",
302
+ isDefault: false,
303
+ config: { botToken: "..." },
304
+ });
305
+ await client.updateChannel(ch._id, { isDefault: true });
306
+ await client.registerWebhook(ch._id, { baseUrl: "https://example.com" }); // telegram only
307
+ await client.channels.typing("chatlu", { roomId: "!abcdef:chatlu.lan", typing: true });
308
+ await client.channels.react("chatlu", {
309
+ roomId: "!abcdef:chatlu.lan",
310
+ eventId: "$event123",
311
+ key: "👀",
312
+ });
313
+ await client.deleteChannel(ch._id);
314
+ ```
315
+
316
+ ## ChatLu profiles, rooms, media & DMs
317
+
318
+ 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:
319
+
320
+ ```typescript
321
+ // Send — file accepts base64 strings, Uint8Array or ArrayBuffer
322
+ const sent = await client.channelMedia("default-chatlu", {
323
+ roomId: "!abcdef:chatlu.lan",
324
+ file: await readFile("cat.png"),
325
+ filename: "cat.png",
326
+ mimetype: "image/png",
327
+ caption: "Look at this", // optional; becomes the event body
328
+ replyToEventId: "$previous", // optional
329
+ threadRootEventId: "$root", // optional
330
+ extraContent: { // optional; only com.agentlu.* is merged
331
+ "com.agentlu.doc": { version: 1, title: "Weekly plan" },
332
+ },
333
+ });
334
+ // sent: { eventId, mxc, roomId, msgtype }
335
+
336
+ // Download (mxc URIs arrive in inbound `media.mxc`)
337
+ const media = await client.channelMediaDownload("default-chatlu", "mxc://chatlu.lan/AbCdEf");
338
+ // media: { contentType, bytes: ArrayBuffer, filename? }
339
+
340
+ // Find or create the bot's DM with a user
341
+ const dm = await client.channelDirectRoom("default-chatlu", "@misa:chatlu.lan");
342
+ // dm: { roomId, created }
343
+
344
+ const profile = await client.channelProfile("agentlu-bot-meal-coach");
345
+ await client.setChannelProfile("agentlu-bot-meal-coach", {
346
+ displayName: "Meal Coach",
347
+ avatar: { base64: imageBase64, mimetype: "image/png", filename: "avatar.png" },
348
+ });
349
+ // An existing Matrix media URI can be used without re-uploading:
350
+ await client.setChannelProfile("agentlu-bot-meal-coach", {
351
+ avatar: { mxc: "mxc://chatlu.lan/AbCdEf" },
352
+ });
353
+
354
+ const rooms = await client.channelRooms("agentlu-bot-meal-coach");
355
+ await client.channelLeave("agentlu-bot-meal-coach", rooms[0].roomId);
356
+
357
+ // Create a private, unencrypted group room from the bot account.
358
+ // Include every bot that will join in `invite` (Synapse requires an invite
359
+ // before the join endpoint can add a bot to a private room).
360
+ const created = await client.channelCreateRoom("agentlu-bot-cradle", {
361
+ name: "Dinner planning",
362
+ invite: ["@larry:chatlu.lan", "@agentlu-bot-meal-coach:chatlu.lan"],
363
+ });
364
+ // created: { roomId, name }
365
+
366
+ // Each invited agent bot joins by room ID; already joined is a no-op success.
367
+ await client.channelJoin("agentlu-bot-meal-coach", created.roomId);
368
+ // { joined: true, roomId }
369
+ ```
370
+
371
+ - `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.
372
+ - `caption` becomes `content.body` and `filename` stays in `info.filename` (Matrix/MSC2530). `info` includes `mimetype`, `size`, and `w`/`h` for PNG/GIF/JPEG.
373
+ - `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).
374
+ - `channelMediaDownload` returns `{ contentType, bytes: ArrayBuffer, filename? }`; the bot token stays on the NotifLu server.
375
+ - `channelDirectRoom` returns `{ roomId, created }`; `created: false` means an existing joined room from `m.direct` was reused.
376
+ - `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.
377
+ - `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.
378
+ - `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.
379
+ - `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.
380
+ - `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`.
381
+
382
+ Secrets in responses are masked (`abcd••••wxyz`).
383
+
384
+ ### Channel config by provider
385
+
386
+ | Provider | Required | Optional |
387
+ |----------|----------|----------|
388
+ | `telegram` | `botToken` | `webhookSecretToken` |
389
+ | `messenger` | `pageAccessToken` | `apiVersion`, `verifyToken`, `appSecret` |
390
+ | `discord` | `webhookUrl` and/or `botToken` | `username` |
391
+ | `line` | `channelAccessToken` | `channelSecret` |
392
+ | `email` | `host`, `user`, `pass` | `port` (587), `secure` (false), `from`, `fromName` |
393
+ | `chatlu` | `homeserverUrl`, `accessToken` | `inbound` (boolean), `forwardReactions` (boolean, default `false`), `allowedInviters` (string[]) |
394
+ | `webpush` | — | `vapidSubject`, `vapidPublicKey`, `vapidPrivateKey`, `ttl` (fallback: `WEBPUSH_VAPID_*` env) |
395
+
396
+ Name: `^[a-zA-Z0-9_-]+$`, not reserved (`telegram` / `messenger` / `discord` / `line` / `email` / `chatlu` / `webpush` / `notiflu`).
397
+
398
+ Email channels send over SMTP and require `options.subject`; `chatId` is the recipient address (alias lookup applies first).
399
+
400
+ 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`.
401
+
402
+ 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`.
403
+
404
+ ## Web push subscriptions
405
+
406
+ 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`.
407
+
408
+ ```typescript
409
+ await client.registerPushSubscription({
410
+ app: "cartlu",
411
+ person: "larry",
412
+ endpoint: sub.endpoint,
413
+ keys: { p256dh: sub.keys.p256dh, auth: sub.keys.auth },
414
+ });
415
+
416
+ const subs = await client.listPushSubscriptions({ app: "cartlu", person: "larry" });
417
+ const one = await client.listPushSubscriptions({ endpoint: sub.endpoint });
418
+ await client.deletePushSubscription({ id: subs[0]._id }); // or { endpoint }
419
+ ```
420
+
421
+ 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.
422
+
423
+ ## Aliases
424
+
425
+ Friendly name → per-channel chat ids.
426
+
427
+ ```typescript
428
+ await client.createAlias({
429
+ name: "larry",
430
+ mappings: { "default-telegram": "123456789", "alerts-discord": "987654321" },
431
+ });
432
+ const aliases = await client.listAliases();
433
+ const people = await client.listAliases({ person: true });
434
+ const misa = await client.listAliases({ name: "misa" });
435
+ await client.updateAlias(id, { mappings: { "default-telegram": "111" } });
436
+ await client.deleteAlias(id);
437
+ ```
438
+
439
+ ## Inbound & Subscriptions
440
+
441
+ Telegram / Messenger / LINE webhooks and ChatLu Matrix sync worker capture inbound messages and fan out to registered webhook subscriptions.
442
+
443
+ ### Inbound responses (history)
444
+
445
+ ```typescript
446
+ const replies = await client.listInbound({ channel: "telegram", matched: true, limit: 20 });
447
+ const full = await client.getInbound(replies[0]._id);
448
+ ```
449
+
450
+ 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:
451
+
452
+ ```typescript
453
+ const media = replies.find((r) => r.media)?.media;
454
+ if (media) {
455
+ const bytes = await client.channelMediaDownload("default-chatlu", media.mxc);
456
+ }
457
+ ```
458
+
459
+ 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.
460
+
461
+ 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`.
462
+
463
+ ### Inbound subscriptions (webhook fanout)
464
+
465
+ Register endpoints to receive normalized inbound messages with HMAC-SHA256 signature verification:
466
+
467
+ ```typescript
468
+ const sub = await client.inbound.subscribe({
469
+ channel: "chatlu",
470
+ url: "http://localhost:8799/webhook/chatlu",
471
+ secret: process.env.CHATLU_WEBHOOK_SECRET,
472
+ });
473
+
474
+ const subs = await client.inbound.list({ channel: "chatlu" });
475
+ const deliveries = await client.inbound.listDeliveries({ subscriptionId: sub._id, status: "failed" });
476
+ await client.inbound.unsubscribe(sub._id);
477
+ ```
478
+
479
+ To receive both messages and reactions, explicitly list both Matrix event types; an unfiltered subscription does not receive reactions:
480
+
481
+ ```typescript
482
+ await client.inbound.subscribe({
483
+ channel: "chatlu",
484
+ url: "http://localhost:8799/webhook/chatlu",
485
+ secret: process.env.CHATLU_WEBHOOK_SECRET,
486
+ events: ["m.room.message", "m.reaction"],
487
+ });
488
+ ```
489
+
490
+ Verify signature in receiving webhook handlers:
491
+
492
+ ```typescript
493
+ import { verifySignature } from "@betterlu/notiflu";
494
+
495
+ const isValid = verifySignature(rawBody, req.headers["x-notif-signature"], secret);
496
+ ```
497
+
498
+ ## Health
499
+
500
+ ```typescript
501
+ const h = await client.health();
502
+ // { ok, workerRunning, notificationCount, aliasCount, channelCount, channels, providers, chatluSync? }
503
+ // chatluSync = { running, loops: [{ channelId, channel, active, botUserId, tokenStatus, lastSyncAt, lastErrorAt, lastErrorCode }] }
504
+ // Informational only: a rejected ChatLu token never flips `ok`.
505
+ ```
506
+
507
+ ## Errors
508
+
509
+ ```typescript
510
+ import { NotifError } from "@betterlu/notiflu";
511
+
512
+ try {
513
+ await client.send({ channel: "telegram", message: "" });
514
+ } catch (err) {
515
+ if (err instanceof NotifError) {
516
+ console.error(err.status, err.message); // 400 message is required
517
+ // Events API errors may also expose err.code and err.details,
518
+ // for example "hop_limit" or "schema_invalid".
519
+ } else {
520
+ throw err;
521
+ }
522
+ }
523
+ ```
524
+
525
+ No auth. Inject `fetch` for tests or custom middleware:
526
+
527
+ ```typescript
528
+ const client = new NotifluClient({
529
+ baseUrl: "http://localhost:8778",
530
+ fetch: myFetch,
531
+ });
532
+ ```
533
+
534
+ ## API reference
535
+
536
+ ### `NotifluClient` / `NotifClient`
537
+
538
+ | Method | Returns | Description |
539
+ |--------|---------|-------------|
540
+ | `health()` | `HealthResponse` | Worker + channel list |
541
+ | `events.publish(input, opts?)` | `PublishEventsResult` | Validate and publish one event or a batch; throws on failure |
542
+ | `events.emit(input, opts?)` | `Promise<void>` | Best-effort buffered publish with three background retries; never throws |
543
+ | `events.list(query?)` | `ListEventsResult` | Cursor page ascending by `seq` |
544
+ | `events.get(source, id)` | `NotifluEvent` | Read one event |
545
+ | `events.subscriptions.list(query?)` | `ListEventSubscriptionsResult` | List event subscriptions as `{ subscriptions }` |
546
+ | `events.subscriptions.create(req)` | `EventSubscription` | Create an API-origin event subscription |
547
+ | `events.subscriptions.delete(id)` | `DeleteEventSubscriptionResult` | Delete an API-origin subscription (`{ deleted: true, id }`) |
548
+ | `events.deliveries.list(query?)` | `ListEventDeliveriesResult` | List event deliveries as `{ deliveries }` |
549
+ | `events.redrive(deliveryId)` | `RedriveEventDeliveryResult` | Redrive one dead delivery |
550
+ | `events.redriveSubscription(id, { status? })` | `RedriveEventSubscriptionResult` | Redrive matching deliveries for a subscription |
551
+ | `events.stats()` | `EventStats` | Event lane counters |
552
+ | `send(req)` | `Notification` | Enqueue (202, or 200 when settled / deduped) |
553
+ | `notify(message, opts?)` | `Notification` | Shorthand for `send` |
554
+ | `notifyTelegramHtml(user, html)` | `Notification` | Telegram HTML to an alias (`userName`) |
555
+ | `escapeHtml(value)` | `string` | Escape `& < > " '` for Telegram HTML |
556
+ | `listNotifications(query?)` | `Notification[]` | Filter queue |
557
+ | `getNotification(id)` | `Notification` | One notification |
558
+ | `retryNotification(id)` | `Notification` | Re-queue a failed send |
559
+ | `deleteNotification(id)` | `Notification` | Delete |
560
+ | `listChannels()` | `Channel[]` | All channels |
561
+ | `getChannel(id)` | `Channel` | One channel (secrets masked) |
562
+ | `createChannel(req)` | `Channel` | Create |
563
+ | `updateChannel(id, req)` | `Channel` | Partial update |
564
+ | `deleteChannel(id)` | `Channel` | Delete |
565
+ | `registerWebhook(id, req?)` | `RegisterWebhookResult` | Telegram `setWebhook` |
566
+ | `channels.typing(name, req)` | `ChannelTypingResult` | Send typing indicator |
567
+ | `channels.react(name, req)` | `ChannelReactionResult` | Send an emoji reaction (`m.annotation`) |
568
+ | `channelMedia(name, req)` / `channels.media(name, req)` | `ChannelMediaResult` | Upload + send a Matrix media message (direct) |
569
+ | `channelMediaDownload(name, mxc)` / `channels.downloadMedia(name, mxc)` | `ChannelMediaDownloadResult` | Download media bytes by `mxc` |
570
+ | `channelDirectRoom(name, userId)` / `channels.directRoom(name, userId)` | `ChannelDirectRoomResult` | Find or create a DM |
571
+ | `channelProfile(name)` | `ChannelProfile` | Get the bot's Matrix profile |
572
+ | `setChannelProfile(name, req)` | `ChannelProfile` | Update display name and/or avatar |
573
+ | `channelRooms(name)` | `ChannelRoom[]` | List joined rooms (up to 200) |
574
+ | `channelRoomMessages(name, roomId, { limit? })` | `ChannelRoomMessages` | Read recent room messages as the bot (newest first) |
575
+ | `channelCreateRoom(name, req)` | `ChannelCreatedRoom` | Create a private, unencrypted group room |
576
+ | `channelJoin(name, roomId)` | `ChannelJoinResult` | Join a room by ID (idempotent) |
577
+ | `channelLeave(name, roomId)` | `ChannelLeaveResult` | Leave and forget a room |
578
+ | `registerPushSubscription(req)` | `PushSubscription` | Upsert a web push subscription by endpoint |
579
+ | `listPushSubscriptions(query?)` | `PushSubscription[]` | Filter by `person`, `app`, `endpoint`, `limit` |
580
+ | `deletePushSubscription({ id?, endpoint? })` | `PushSubscription` | Delete a subscription |
581
+ | `listAliases(query?)` | `Alias[]` | Filter by `person`, `name`, `limit` |
582
+ | `getAlias(id)` | `Alias` | One alias |
583
+ | `createAlias(req)` | `Alias` | Create |
584
+ | `updateAlias(id, req)` | `Alias` | Update |
585
+ | `deleteAlias(id)` | `Alias` | Delete |
586
+ | `listInbound(query?)` | `InboundResponse[]` | Inbound events (no `rawPayload`) |
587
+ | `getInbound(id)` | `InboundResponse` | One inbound (includes `rawPayload`) |
588
+ | `inbound.subscribe(req)` | `InboundSubscription` | Register inbound webhook |
589
+ | `inbound.list(query?)` | `InboundSubscription[]` | List inbound subscriptions |
590
+ | `inbound.unsubscribe(id)` | `InboundSubscription` | Delete inbound subscription |
591
+ | `inbound.listDeliveries(query?)` | `InboundDelivery[]` | List delivery status and history |
592
+ | `app.people()` | `AppPerson[]` | List Larry/Misa and 30-day feed counts |
593
+ | `app.registerDevice(req)` / `app.unregisterDevice(installationId)` | `AppDevice` | Register or remove an Android installation |
594
+ | `app.feed(query)` | `AppFeedPage` | Read correlated, cursor-paginated NotifLu items |
595
+ | `app.detail(id, person)` | `AppNotificationDetail` | Read full message, device engagement, and replies |
596
+ | `app.markRead(id, person)` / `app.readAll(person, before?)` | read result | Update per-person read state |
597
+ | `app.event(id, req)` | `AppEventResult` | Record delivery/open/dismiss/action (actions fan out to inbound subscriptions) |
598
+ | `app.sources(person)` | `AppSourceSummary[]` | Seven-day source summary |
599
+ | `app.testPush(installationId)` | `AppTestPushResult` | Queue one-device FCM test |
600
+
601
+ ### Standalone exports
602
+
603
+ - `verifySignature(rawBody, signatureHeader, secret): boolean`
604
+ - `parseEventDelivery({ headers, body?, rawBody?, secret? }): ParsedEventDelivery`
605
+ - `createEventDeduper({ max? }): EventDeduper` — `seen(event)` is `true` for duplicate `(source, id)` keys
606
+ - `NotifClient` is the 1.x compatibility export; `NotifluClient` is the preferred alias
607
+
608
+ ### NotifLu example
609
+
610
+ ```typescript
611
+ await client.app.registerDevice({
612
+ installationId: "android-install-1",
613
+ person: "larry",
614
+ fcmToken,
615
+ deviceName: "Pixel",
616
+ });
617
+
618
+ const feed = await client.app.feed({ person: "larry", scope: "mine", limit: 30 });
619
+ if (feed.items[0]) await client.app.markRead(feed.items[0].id, "larry");
620
+ ```
621
+
622
+ `FCM_SERVICE_ACCOUNT_JSON` configures the server-side `notiflu` provider. Device registration responses never return FCM tokens.
623
+
624
+ ## License
625
+
626
+ MIT