@12-apps/messaging 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -177,6 +177,8 @@ with `setTranscript` (it is deleted with the text), and drop the buffer.
177
177
  |---|---|
178
178
  | `@12-apps/messaging` | `createMessagingEngine`, the ports, the store port with `createPrismaMessagingStore` and `createMemoryMessagingStore`, the adapter interface, the errors, the types. |
179
179
  | `@12-apps/messaging/whatsapp` | `createWhatsAppAdapter`, and standalone: `verifyMetaSignature`, `verifyMetaSubscription`, `parseWhatsAppPayload`, `parseWhatsAppStatuses`, `isOptOutText`, the Graph sender, `downloadWhatsAppMedia`, and the Embedded Signup helpers `exchangeSignupCode`, `readSignupAccounts`, `subscribeAppToWaba`. |
180
+ | `@12-apps/messaging/whatsapp-web` | UNOFFICIAL. `createWhatsAppWebSession` (a linked device over Baileys), `createWhatsAppWebAdapter` (the same `ChannelAdapter`), `createMemoryAuthStateStore`, and the pure `normalizeUpsert`, `normalizeUpdates`, `encodeEnvelope`, `parseEnvelope`. See below. |
181
+ | `@12-apps/messaging/inbound-guard` | `normalizeInbound`, `screenInbound`, `DEFAULT_INBOUND_RULES`, `wrapForAgent`, `parseClassification`: the screen a host runs on untrusted inbound text before a model reads it. Pure, no I/O, no channel. |
180
182
  | `@12-apps/messaging/server` | `createApiMessaging` (the webhook route pair, in `@12-apps/wiring`'s `WireRoute` shape) and `MESSAGING_JOBS`. |
181
183
  | `@12-apps/messaging/manifest`, `/manifest/server` | The wiring manifests. |
182
184
 
@@ -184,6 +186,159 @@ The signature check and the receipt parser are exported on their own because a
184
186
  host that sends WhatsApp messages some other way (a platform notification
185
187
  number) needs exactly those two and nothing else.
186
188
 
189
+ ## WhatsApp Web (unofficial)
190
+
191
+ `@12-apps/messaging/whatsapp-web` is a second transport for WhatsApp. It is a linked device over the WhatsApp Web protocol, through [Baileys](https://github.com/WhiskeySockets/Baileys) (MIT). It sits beside the Cloud API adapter and has the same `ChannelAdapter` contract, so a host switches a number between the two by mounting one adapter or the other.
192
+
193
+ **Read this before using it:**
194
+ - **It is not Meta's API.** WhatsApp's terms forbid unofficial clients, and the number it runs on can be banned. Never put a store's only number on it without the store owner's informed yes.
195
+ - **A linked session's keys are the whole account.** Whoever holds the auth state reads and sends every chat. The package writes no key itself: the host passes an `AuthStateStore` and decides where it lives (an encrypted column, a secrets manager). Nothing is logged or put in an error.
196
+ - **A personal account carries other people's messages.** Where they are kept, and for how long, is the host's decision.
197
+
198
+ **Baileys is not a dependency.** The host installs `baileys` (v7) and passes the module in. The package never imports it, and a test fails if a source file does.
199
+
200
+ ```ts
201
+ import * as baileys from "baileys";
202
+ import { createWhatsAppWebAdapter, createWhatsAppWebSession } from "@12-apps/messaging/whatsapp-web";
203
+
204
+ const session = createWhatsAppWebSession({
205
+ baileys,
206
+ authStore, // the host's, sealed
207
+ deliver: (rawBody) => engine.receive("whatsapp", rawBody),
208
+ onStatus: (status) => showPairing(status), // qr | pairing-code | open | logged-out | failed …
209
+ });
210
+ await session.start();
211
+ const engine = createMessagingEngine({ adapters: [createWhatsAppWebAdapter({ sessions: session })], /* … */ });
212
+ ```
213
+
214
+ | | |
215
+ |---|---|
216
+ | **Pairing** | `onStatus` reports `qr`: show it on the phone under *Linked devices › Link a device*. With `pairingPhoneNumber`, the session asks ONCE for a code instead (`pairing-code`). After pairing, `creds.update` is saved on every change, and the next `start()` resumes without pairing. |
217
+ | **Inbound** | Each live socket event is normalized into the SAME `NormalizedEvent`s the Cloud parser produces, then handed to `deliver` as a small JSON envelope, in socket order. The envelope holds no Baileys objects and no media keys. The inbox, dedupe, processing job and retention are the engine's, unchanged. A failed `deliver` is reported through `onError`, because a socket does not redeliver. |
218
+ | **What is skipped** | Groups, broadcasts, Status, channels, the account's own messages (`fromMe`), history sync (`append`) and protocol messages. The engine's conversation is one contact. |
219
+ | **Outbound** | `send` goes through the session's socket. Personal accounts have no buttons or lists, so `BUTTONS` and `LIST` become numbered lines under the text, and the answer arrives as `TEXT`. Failures are `ChannelSendFailure`: `NOT_CONNECTED`, the socket's code, or `NO_MESSAGE_ID`. |
220
+ | **Receipts** | `messages.update` on our own messages maps to `SENT` / `DELIVERED` / `READ` / `FAILED`. |
221
+ | **Media** | The last `mediaCacheSize` (200) audio messages stay in memory. `fetchMedia` downloads by message id, with the size cap and the deadline. After a restart an older audio is `NOT_FOUND`. |
222
+ | **Reconnects** | An unexpected close reconnects with exponential backoff (5 attempts from 2 s), and 515 (restart after pairing) reconnects at once. 401 (logged out) clears the keys and stops. 440 (replaced) and 403 stop. |
223
+ | **Webhook** | None. `verify` fails closed, so the webhook route answers 401 to any POST for the channel. |
224
+ | **Policy** | No service window by default (`OPEN_SEND_POLICY`); the 24 h window is a Business API rule. |
225
+ | **Channel key** | `whatsapp` by default, so the switch keeps the connections and conversations. Pass `kind: "whatsapp-web"` to run both side by side. The connection's credential is unused: the keys live in the auth store. |
226
+
227
+ ## Screening inbound text before a model reads it
228
+
229
+ `@12-apps/messaging/inbound-guard` is for a host that hands inbound messages
230
+ (a DM, a WhatsApp text, any channel) to a model, to classify them or to answer
231
+ them. Text from outside is untrusted: it can carry instructions aimed at the
232
+ model ("ignore previous instructions", a fake system line, a base64 blob). The
233
+ module does not make a model safe on its own; the protection that matters is
234
+ that the model holds no credential and calls no write API. What it adds is a
235
+ deterministic screen in front of the model and a fixed shape for what comes
236
+ back. Every function is pure: no I/O, no clock, no host names.
237
+
238
+ ### The contract
239
+
240
+ 1. **`normalizeInbound(text)`** removes what renders as nothing (zero-width,
241
+ bidi, control characters; Unicode tag characters, whose hidden ASCII is
242
+ decoded), applies NFKC (full-width and styled letters become plain), folds
243
+ Cyrillic and Greek look-alikes inside words spoofing Latin, and decodes
244
+ base64, hex and letter-escaping URL runs (two levels deep) into `decoded`
245
+ views. `text` is what a model may be shown; `folded` (lower case, no
246
+ accents) is what the rules read.
247
+ 2. **`screenInbound(text, { recentFromSender?, rules?, thresholds?, weakCap?, scanLimit? })`**
248
+ returns `{ risk: "low" | "medium" | "high", reasons, score, normalized }`.
249
+ Each rule in `DEFAULT_INBOUND_RULES` is a named entry with a weight; the
250
+ score is the sum of the rules that tripped, compared with
251
+ `DEFAULT_THRESHOLDS` (`medium` from 1, `high` from 3). A rule counts once,
252
+ whichever reading tripped it: the folded text, its leetspeak reading, the
253
+ same words with markup, punctuation and emoji read as spaces, its
254
+ letters-only reading, or a decoded run (reported as `<id>:<encoding>`).
255
+ The pattern rules read the first `DEFAULT_SCAN_LIMIT` (8000) characters;
256
+ anything longer is `high` through the length rules already, so a host that
257
+ replaces `rules` must keep the length rules (or raise `scanLimit`): the
258
+ text past the limit is never scanned. The rules
259
+ cover, in pt-BR and English: instructions aimed at the reader, references
260
+ to its prompt, new roles, dictating its answer, fake data boundaries,
261
+ chat-template, tool and role-line markup, requests for other people's
262
+ records, secrets, infrastructure and tool names, SQL, shell commands, code
263
+ fences, links and shorteners, claims to speak for a platform or the staff,
264
+ length, invisible characters, look-alike letters, encoded runs, and bursts
265
+ (the caller counts the sender's recent messages and passes
266
+ `recentFromSender`; `burst` with `flood` withholds on its own, so the
267
+ caller's window decides how many messages that is).
268
+
269
+ Rules a customer also trips are marked `weak` (a link, a password or token,
270
+ "a partir de agora", "você é um robô?", dismissing their own earlier
271
+ instructions, "sou do time…", a message opening with "Sistema:" or with a
272
+ platform's team as its signature). When every rule a message trips is
273
+ weak, its risk is capped at `DEFAULT_WEAK_CAP` (`medium`, `weakCap` to
274
+ move it), however many add up: weak signals alone never withhold a
275
+ message. One rule aimed at the reader (an override of its instructions, a
276
+ new role, a fake system turn, an encoded payload, a dictated answer)
277
+ lifts the cap.
278
+
279
+ What ordinary customer text scores: most of it is `low`. A message with
280
+ one weak signal is `medium`: asking whether it talks to a bot ("você é um
281
+ robô?"), "a partir de agora…", dismissing its own earlier instructions
282
+ ("desconsidere as instruções anteriores, mudei o endereço"), a link, a
283
+ bare "senha" or "token", "sou da equipe…". None of those is `high`, alone
284
+ or together;
285
+ a gate, doorbell, wifi or app password and a payment key are not secrets
286
+ at all. `false-positives.json` holds the measured examples.
287
+ 3. **`wrapForAgent(messages, { delimiter? })`** builds the prompt section for
288
+ one model call. A `low` or `medium` message appears as its normalized text
289
+ between `<<<DELIM` and `DELIM>>>`, under one fixed rule line saying those
290
+ blocks are data. `DELIM` is drawn fresh per call from the platform CSPRNG
291
+ (128 bits); a message containing it is refused with
292
+ `DelimiterCollisionError`. A `high` message is never shown: its entry
293
+ carries only the sender's handle, the time, the length and the reasons.
294
+ The handle is the sender's own text, so it is screened too: a handle that
295
+ trips any rule, or carries characters outside `[A-Za-z0-9._@+:-]`, is
296
+ shown as an opaque `sender-<n>` (the same one for the same handle within a
297
+ batch) with `senderWithheld: true`, and a withheld message adds the reason
298
+ `sender-handle`. The rule line declares the header values data as well.
299
+ 4. **`parseClassification(answer, { ids? })`** accepts exactly
300
+ `{ id, category: duvida | reclamacao | lead | elogio | spam | suspeita,
301
+ urgency: hoje | normal, summary, needs_human: boolean }`, with a non-empty
302
+ summary of at most 200 characters carrying no e-mail, phone number or link,
303
+ and (given `ids`) an id that was sent. Anything else is
304
+ `{ ok: false, error: { code, field?, message } }`, which the host reports
305
+ in its own words and drops.
306
+
307
+ ### How a host uses it
308
+
309
+ ```ts
310
+ import {
311
+ screenInbound,
312
+ wrapForAgent,
313
+ parseClassification,
314
+ } from "@12-apps/messaging/inbound-guard";
315
+
316
+ const screened = inbound.map((m) => ({
317
+ ...m,
318
+ screen: screenInbound(m.text, { recentFromSender: m.recentCount }),
319
+ }));
320
+ // A conversational host routes a `high` message to a person, never to the model.
321
+ const batch = wrapForAgent(screened);
322
+ const answer = await model(`${instructions}\n\n${batch.prompt}`);
323
+ const result = parseClassification(answer, { ids: screened.map((m) => m.id) });
324
+ if (!result.ok) reportInvalid(result.error); // the host's own copy
325
+ ```
326
+
327
+ To tune the screen, pass your own list (`[...DEFAULT_INBOUND_RULES, mine]`, or
328
+ a filtered copy) and thresholds; a rule is data (`kind: "pattern"` with
329
+ regular expressions written against the folded view, or a signal kind with an
330
+ `atLeast`).
331
+
332
+ ### The fixtures
333
+
334
+ `src/inbound-guard/__tests__/fixtures/red-team.json` holds injection attempts
335
+ (pt-BR and English; plain, zero-width, homoglyph, full-width, base64, hex,
336
+ URL-encoded, tag characters, split across lines, letter-spaced, leetspeak):
337
+ each must come out `high`, or, marked `"expect": "wrapped"`, reach the model
338
+ only as quoted data. `false-positives.json` holds ordinary customer messages
339
+ that must never be `high`, each with the highest risk it may take. Both files
340
+ document their format in `$format`; append cases and the suite runs them.
341
+
187
342
  ## Tests
188
343
 
189
344
  `src/**/__tests__`, vitest. The pipeline, the sender and the retention sweep