@12-apps/messaging 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -177,6 +177,7 @@ 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/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
181
  | `@12-apps/messaging/server` | `createApiMessaging` (the webhook route pair, in `@12-apps/wiring`'s `WireRoute` shape) and `MESSAGING_JOBS`. |
181
182
  | `@12-apps/messaging/manifest`, `/manifest/server` | The wiring manifests. |
182
183
 
@@ -184,6 +185,121 @@ The signature check and the receipt parser are exported on their own because a
184
185
  host that sends WhatsApp messages some other way (a platform notification
185
186
  number) needs exactly those two and nothing else.
186
187
 
188
+ ## Screening inbound text before a model reads it
189
+
190
+ `@12-apps/messaging/inbound-guard` is for a host that hands inbound messages
191
+ (a DM, a WhatsApp text, any channel) to a model, to classify them or to answer
192
+ them. Text from outside is untrusted: it can carry instructions aimed at the
193
+ model ("ignore previous instructions", a fake system line, a base64 blob). The
194
+ module does not make a model safe on its own; the protection that matters is
195
+ that the model holds no credential and calls no write API. What it adds is a
196
+ deterministic screen in front of the model and a fixed shape for what comes
197
+ back. Every function is pure: no I/O, no clock, no host names.
198
+
199
+ ### The contract
200
+
201
+ 1. **`normalizeInbound(text)`** removes what renders as nothing (zero-width,
202
+ bidi, control characters; Unicode tag characters, whose hidden ASCII is
203
+ decoded), applies NFKC (full-width and styled letters become plain), folds
204
+ Cyrillic and Greek look-alikes inside words spoofing Latin, and decodes
205
+ base64, hex and letter-escaping URL runs (two levels deep) into `decoded`
206
+ views. `text` is what a model may be shown; `folded` (lower case, no
207
+ accents) is what the rules read.
208
+ 2. **`screenInbound(text, { recentFromSender?, rules?, thresholds?, weakCap?, scanLimit? })`**
209
+ returns `{ risk: "low" | "medium" | "high", reasons, score, normalized }`.
210
+ Each rule in `DEFAULT_INBOUND_RULES` is a named entry with a weight; the
211
+ score is the sum of the rules that tripped, compared with
212
+ `DEFAULT_THRESHOLDS` (`medium` from 1, `high` from 3). A rule counts once,
213
+ whichever reading tripped it: the folded text, its leetspeak reading, the
214
+ same words with markup, punctuation and emoji read as spaces, its
215
+ letters-only reading, or a decoded run (reported as `<id>:<encoding>`).
216
+ The pattern rules read the first `DEFAULT_SCAN_LIMIT` (8000) characters;
217
+ anything longer is `high` through the length rules already, so a host that
218
+ replaces `rules` must keep the length rules (or raise `scanLimit`): the
219
+ text past the limit is never scanned. The rules
220
+ cover, in pt-BR and English: instructions aimed at the reader, references
221
+ to its prompt, new roles, dictating its answer, fake data boundaries,
222
+ chat-template, tool and role-line markup, requests for other people's
223
+ records, secrets, infrastructure and tool names, SQL, shell commands, code
224
+ fences, links and shorteners, claims to speak for a platform or the staff,
225
+ length, invisible characters, look-alike letters, encoded runs, and bursts
226
+ (the caller counts the sender's recent messages and passes
227
+ `recentFromSender`; `burst` with `flood` withholds on its own, so the
228
+ caller's window decides how many messages that is).
229
+
230
+ Rules a customer also trips are marked `weak` (a link, a password or token,
231
+ "a partir de agora", "você é um robô?", dismissing their own earlier
232
+ instructions, "sou do time…", a message opening with "Sistema:" or with a
233
+ platform's team as its signature). When every rule a message trips is
234
+ weak, its risk is capped at `DEFAULT_WEAK_CAP` (`medium`, `weakCap` to
235
+ move it), however many add up: weak signals alone never withhold a
236
+ message. One rule aimed at the reader (an override of its instructions, a
237
+ new role, a fake system turn, an encoded payload, a dictated answer)
238
+ lifts the cap.
239
+
240
+ What ordinary customer text scores: most of it is `low`. A message with
241
+ one weak signal is `medium`: asking whether it talks to a bot ("você é um
242
+ robô?"), "a partir de agora…", dismissing its own earlier instructions
243
+ ("desconsidere as instruções anteriores, mudei o endereço"), a link, a
244
+ bare "senha" or "token", "sou da equipe…". None of those is `high`, alone
245
+ or together;
246
+ a gate, doorbell, wifi or app password and a payment key are not secrets
247
+ at all. `false-positives.json` holds the measured examples.
248
+ 3. **`wrapForAgent(messages, { delimiter? })`** builds the prompt section for
249
+ one model call. A `low` or `medium` message appears as its normalized text
250
+ between `<<<DELIM` and `DELIM>>>`, under one fixed rule line saying those
251
+ blocks are data. `DELIM` is drawn fresh per call from the platform CSPRNG
252
+ (128 bits); a message containing it is refused with
253
+ `DelimiterCollisionError`. A `high` message is never shown: its entry
254
+ carries only the sender's handle, the time, the length and the reasons.
255
+ The handle is the sender's own text, so it is screened too: a handle that
256
+ trips any rule, or carries characters outside `[A-Za-z0-9._@+:-]`, is
257
+ shown as an opaque `sender-<n>` (the same one for the same handle within a
258
+ batch) with `senderWithheld: true`, and a withheld message adds the reason
259
+ `sender-handle`. The rule line declares the header values data as well.
260
+ 4. **`parseClassification(answer, { ids? })`** accepts exactly
261
+ `{ id, category: duvida | reclamacao | lead | elogio | spam | suspeita,
262
+ urgency: hoje | normal, summary, needs_human: boolean }`, with a non-empty
263
+ summary of at most 200 characters carrying no e-mail, phone number or link,
264
+ and (given `ids`) an id that was sent. Anything else is
265
+ `{ ok: false, error: { code, field?, message } }`, which the host reports
266
+ in its own words and drops.
267
+
268
+ ### How a host uses it
269
+
270
+ ```ts
271
+ import {
272
+ screenInbound,
273
+ wrapForAgent,
274
+ parseClassification,
275
+ } from "@12-apps/messaging/inbound-guard";
276
+
277
+ const screened = inbound.map((m) => ({
278
+ ...m,
279
+ screen: screenInbound(m.text, { recentFromSender: m.recentCount }),
280
+ }));
281
+ // A conversational host routes a `high` message to a person, never to the model.
282
+ const batch = wrapForAgent(screened);
283
+ const answer = await model(`${instructions}\n\n${batch.prompt}`);
284
+ const result = parseClassification(answer, { ids: screened.map((m) => m.id) });
285
+ if (!result.ok) reportInvalid(result.error); // the host's own copy
286
+ ```
287
+
288
+ To tune the screen, pass your own list (`[...DEFAULT_INBOUND_RULES, mine]`, or
289
+ a filtered copy) and thresholds; a rule is data (`kind: "pattern"` with
290
+ regular expressions written against the folded view, or a signal kind with an
291
+ `atLeast`).
292
+
293
+ ### The fixtures
294
+
295
+ `src/inbound-guard/__tests__/fixtures/red-team.json` holds injection attempts
296
+ (pt-BR and English; plain, zero-width, homoglyph, full-width, base64, hex,
297
+ URL-encoded, tag characters, split across lines, letter-spaced, leetspeak):
298
+ each must come out `high`, or, marked `"expect": "wrapped"`, reach the model
299
+ only as quoted data. `false-positives.json` holds ordinary customer messages
300
+ that must never be `high`, each with the highest risk it may take. Both files
301
+ document their format in `$format`; append cases and the suite runs them.
302
+
187
303
  ## Tests
188
304
 
189
305
  `src/**/__tests__`, vitest. The pipeline, the sender and the retention sweep
@@ -0,0 +1,254 @@
1
+ /**
2
+ * The encoded runs an inbound message may hide an instruction in: long
3
+ * base64, hex, URL-encoded escapes of letters, and Unicode tag characters
4
+ * (invisible ASCII). Each run is decoded only when the result reads as text,
5
+ * so a payment code, a hash or a tracking id (which decode to bytes, not
6
+ * words) yields nothing.
7
+ */
8
+ type EncodingKind = "base64" | "hex" | "url" | "unicode-tags";
9
+ /** One encoded run found in a message and the text it decodes to. */
10
+ interface DecodedRun {
11
+ readonly encoding: EncodingKind;
12
+ /** The run as it appears in the message. */
13
+ readonly source: string;
14
+ /** What it decodes to. Scanned by the screen like the message itself. */
15
+ readonly text: string;
16
+ }
17
+
18
+ /**
19
+ * `normalizeInbound` — the one view of an untrusted message every later step
20
+ * reads. It removes what renders as nothing (zero-width, bidi and control
21
+ * characters, Unicode tags), applies NFKC (full-width and styled letters
22
+ * become plain ones), folds Cyrillic and Greek look-alikes inside words that
23
+ * are spoofing Latin, and decodes obvious encoded runs into extra views the
24
+ * screen also scans. Pure: no I/O, no clock, no randomness.
25
+ */
26
+
27
+ interface NormalizedInbound {
28
+ /** The message exactly as received. */
29
+ readonly original: string;
30
+ /** Invisibles stripped, NFKC, look-alikes folded, line breaks unified. What an agent may be shown. */
31
+ readonly text: string;
32
+ /** `text` lower-cased, accents removed, whitespace collapsed. What the rules match. */
33
+ readonly folded: string;
34
+ /** Encoded runs that decode to text, at any depth up to two. */
35
+ readonly decoded: readonly DecodedRun[];
36
+ /** Invisible characters removed that have no innocent reading (emoji joiners are not counted). */
37
+ readonly invisibles: number;
38
+ /** Words written with look-alike letters from another script, or styled letters. */
39
+ readonly lookAlikes: number;
40
+ }
41
+ /** Lower case, no accents, one space between words: the text the rules read. */
42
+ declare function foldForMatching(text: string): string;
43
+ /** Normalize one untrusted inbound message. Never throws. */
44
+ declare function normalizeInbound(text: string): NormalizedInbound;
45
+
46
+ /** The shapes of the screen's rules; the lists themselves are in `rules*.ts`. */
47
+ type InboundRisk = "low" | "medium" | "high";
48
+ /** A rule that matches the message's words. */
49
+ interface PatternRule {
50
+ readonly id: string;
51
+ readonly kind: "pattern";
52
+ readonly weight: number;
53
+ readonly description: string;
54
+ readonly patterns: readonly RegExp[];
55
+ /** Needles for the letters-and-digits-only view. Keep them long (12+): short ones match across words. */
56
+ readonly compact?: readonly string[];
57
+ /**
58
+ * A signal customers also give (a link, a password, "a partir de agora",
59
+ * dismissing their own earlier message). When every rule a message trips is
60
+ * weak, its risk is capped at `DEFAULT_WEAK_CAP`: weak signals alone never
61
+ * withhold a message, however many add up.
62
+ */
63
+ readonly weak?: boolean;
64
+ }
65
+ /** A rule on a measured property of the message rather than its words. */
66
+ interface SignalRule {
67
+ readonly id: string;
68
+ readonly kind: "length" | "burst" | "encoded" | "invisible" | "look-alike";
69
+ readonly weight: number;
70
+ readonly description: string;
71
+ /** Trips at this value or above: characters, recent messages, decoded runs, characters, words. */
72
+ readonly atLeast: number;
73
+ /**
74
+ * A signal customers also give (a link, a password, "a partir de agora",
75
+ * dismissing their own earlier message). When every rule a message trips is
76
+ * weak, its risk is capped at `DEFAULT_WEAK_CAP`: weak signals alone never
77
+ * withhold a message, however many add up.
78
+ */
79
+ readonly weak?: boolean;
80
+ }
81
+ type InboundRule = PatternRule | SignalRule;
82
+ interface ScreenThresholds {
83
+ /** A score at or above this is `medium`. */
84
+ readonly medium: number;
85
+ /** A score at or above this is `high`: the text never reaches a model. */
86
+ readonly high: number;
87
+ }
88
+ declare const DEFAULT_THRESHOLDS: ScreenThresholds;
89
+ /** The highest risk a message reaches when only `weak` rules tripped. */
90
+ declare const DEFAULT_WEAK_CAP: InboundRisk;
91
+ /**
92
+ * How many characters of the folded text (and of each decoded run) the
93
+ * pattern rules read. Longer input already trips the length rules
94
+ * (`extreme-length` alone with `excessive-length` is `high`), so the tail adds
95
+ * nothing but time. A host that replaces the rule list keeps the length rules
96
+ * (or raises this limit): the tail past it is never scanned.
97
+ */
98
+ declare const DEFAULT_SCAN_LIMIT = 8000;
99
+
100
+ /**
101
+ * The screen's rules, as data. Each rule is a named entry with a weight; the
102
+ * screen sums the weights of the rules a message trips and compares the sum
103
+ * with `DEFAULT_THRESHOLDS`. A host overrides either by passing its own list
104
+ * (`screenInbound(text, { rules: [...DEFAULT_INBOUND_RULES, mine] })`).
105
+ *
106
+ * Patterns are written against the FOLDED view (lower case, no accents, one
107
+ * space between words), so they are plain ASCII and match "instruções",
108
+ * "INSTRUCOES" and "instrucoes" alike. The screen also runs them over the
109
+ * same text with every run of punctuation, markup or emoji read as one space,
110
+ * and matches `compact` needles against it with everything but letters and
111
+ * digits removed, which is how a phrase split letter by letter is still found.
112
+ */
113
+
114
+ /** The default rule list, in the order reasons are reported. */
115
+ declare const DEFAULT_INBOUND_RULES: readonly InboundRule[];
116
+
117
+ /**
118
+ * `screenInbound` — the deterministic risk screen. It normalizes the message,
119
+ * runs every rule over the folded text, its leetspeak reading, its
120
+ * letters-only reading and every decoded run, and sums the weights of the
121
+ * rules that tripped. Pure and synchronous: the same text and options always
122
+ * give the same answer.
123
+ */
124
+
125
+ interface ScreenOptions {
126
+ /** Replaces the rule list. Extend with `[...DEFAULT_INBOUND_RULES, mine]`. */
127
+ readonly rules?: readonly InboundRule[];
128
+ readonly thresholds?: ScreenThresholds;
129
+ /** The highest risk when only `weak` rules tripped. Default `DEFAULT_WEAK_CAP`; `"high"` turns the cap off. */
130
+ readonly weakCap?: InboundRisk;
131
+ /** How many messages this sender sent recently, this one included. The caller picks the window. */
132
+ readonly recentFromSender?: number;
133
+ /** Characters of the folded text (and of each decoded run) the pattern rules read. Default `DEFAULT_SCAN_LIMIT`. */
134
+ readonly scanLimit?: number;
135
+ }
136
+ interface ScreenResult {
137
+ readonly risk: InboundRisk;
138
+ /** The ids of the rules that tripped; `<id>:<encoding>` when only a decoded run tripped it. */
139
+ readonly reasons: readonly string[];
140
+ readonly score: number;
141
+ readonly normalized: NormalizedInbound;
142
+ }
143
+ /** `risk`, lowered to `cap` when every tripped rule is weak. */
144
+ declare function capWeak(risk: InboundRisk, tripped: readonly InboundRule[], cap: InboundRisk): InboundRisk;
145
+ declare function riskOf(score: number, thresholds: ScreenThresholds): InboundRisk;
146
+ /** Screen one untrusted inbound message. */
147
+ declare function screenInbound(text: string, opts?: ScreenOptions): ScreenResult;
148
+
149
+ /**
150
+ * `wrapForAgent` — what a model is allowed to read of a batch of untrusted
151
+ * messages. A `low` or `medium` message is quoted as data between two lines
152
+ * carrying a per-call random delimiter, under one fixed rule line that says
153
+ * so. A `high` message is never shown: only who sent it, when, how long it
154
+ * was and why it was withheld. The sender's handle is chosen by the sender,
155
+ * so it is screened too: one that trips any rule, or carries characters the
156
+ * header cannot hold, is replaced by an opaque `sender-<n>`.
157
+ */
158
+
159
+ interface InboundForAgent {
160
+ readonly id: string;
161
+ readonly senderHandle: string;
162
+ readonly time: Date | string;
163
+ readonly text: string;
164
+ /** A screen already run on this same `text` (another text is refused). Omitted, the message is screened here. */
165
+ readonly screen?: ScreenResult;
166
+ /** Passed to the screen when it runs here. */
167
+ readonly recentFromSender?: number;
168
+ }
169
+ interface WrapOptions {
170
+ /** A fixed delimiter, for tests. Omitted, a fresh crypto-random one is drawn per call. */
171
+ readonly delimiter?: string;
172
+ /** Rules and thresholds for messages screened here. */
173
+ readonly screen?: Omit<ScreenOptions, "recentFromSender">;
174
+ }
175
+ type WrappedEntry = {
176
+ readonly kind: "data";
177
+ readonly id: string;
178
+ /** The handle as received, or `sender-<n>` when it was withheld. */
179
+ readonly senderHandle: string;
180
+ readonly senderWithheld: boolean;
181
+ readonly time: string;
182
+ readonly risk: Exclude<InboundRisk, "high">;
183
+ readonly text: string;
184
+ } | {
185
+ readonly kind: "withheld";
186
+ readonly id: string;
187
+ readonly senderHandle: string;
188
+ readonly senderWithheld: boolean;
189
+ readonly time: string;
190
+ readonly length: number;
191
+ readonly reasons: readonly string[];
192
+ };
193
+ interface WrappedBatch {
194
+ readonly delimiter: string;
195
+ /** The prompt section: the rule line, then each entry. */
196
+ readonly prompt: string;
197
+ readonly entries: readonly WrappedEntry[];
198
+ }
199
+ declare class DelimiterCollisionError extends Error {
200
+ readonly messageId: string;
201
+ constructor(messageId: string);
202
+ }
203
+ /** The rule line. Fixed text: nothing a sender wrote is ever part of it. */
204
+ declare function wrapRuleLine(delimiter: string): string;
205
+ /** A fresh delimiter: 128 bits from the platform's CSPRNG. */
206
+ declare function randomDelimiter(): string;
207
+ /**
208
+ * Wrap a batch for one model call. Throws `DelimiterCollisionError` when a
209
+ * message that would be shown contains the delimiter, and a `TypeError` for a
210
+ * delimiter that is not 16-128 characters of `[A-Za-z0-9_-]` or for a given
211
+ * screen that was run on other text.
212
+ */
213
+ declare function wrapForAgent(messages: readonly InboundForAgent[], opts?: WrapOptions): WrappedBatch;
214
+
215
+ /**
216
+ * `parseClassification` — the only shape a classifying agent's answer may
217
+ * take. Anything else (bad JSON, a missing or extra field, a value outside
218
+ * its set, a summary over 200 characters or carrying contact data) comes back
219
+ * as a typed error the caller reports and drops; nothing the agent wrote
220
+ * outside the schema reaches a person or a tool.
221
+ */
222
+ declare const CLASSIFICATION_CATEGORIES: readonly ["duvida", "reclamacao", "lead", "elogio", "spam", "suspeita"];
223
+ declare const CLASSIFICATION_URGENCIES: readonly ["hoje", "normal"];
224
+ declare const SUMMARY_MAX_LENGTH = 200;
225
+ type ClassificationCategory = (typeof CLASSIFICATION_CATEGORIES)[number];
226
+ type ClassificationUrgency = (typeof CLASSIFICATION_URGENCIES)[number];
227
+ interface Classification {
228
+ readonly id: string;
229
+ readonly category: ClassificationCategory;
230
+ readonly urgency: ClassificationUrgency;
231
+ readonly summary: string;
232
+ readonly needs_human: boolean;
233
+ }
234
+ type ClassificationErrorCode = "invalid-json" | "not-an-object" | "unknown-field" | "missing-field" | "invalid-field" | "unknown-id";
235
+ interface ClassificationError {
236
+ readonly code: ClassificationErrorCode;
237
+ readonly field?: string;
238
+ readonly message: string;
239
+ }
240
+ type ClassificationResult = {
241
+ readonly ok: true;
242
+ readonly value: Classification;
243
+ } | {
244
+ readonly ok: false;
245
+ readonly error: ClassificationError;
246
+ };
247
+ interface ParseClassificationOptions {
248
+ /** The ids that were sent to the agent. An answer about any other id is refused. */
249
+ readonly ids?: Iterable<string>;
250
+ }
251
+ /** Validate one classification, given as a JSON string or an already-parsed value. */
252
+ declare function parseClassification(input: unknown, opts?: ParseClassificationOptions): ClassificationResult;
253
+
254
+ export { CLASSIFICATION_CATEGORIES, CLASSIFICATION_URGENCIES, type Classification, type ClassificationCategory, type ClassificationError, type ClassificationErrorCode, type ClassificationResult, type ClassificationUrgency, DEFAULT_INBOUND_RULES, DEFAULT_SCAN_LIMIT, DEFAULT_THRESHOLDS, DEFAULT_WEAK_CAP, type DecodedRun, DelimiterCollisionError, type EncodingKind, type InboundForAgent, type InboundRisk, type InboundRule, type NormalizedInbound, type ParseClassificationOptions, type PatternRule, SUMMARY_MAX_LENGTH, type ScreenOptions, type ScreenResult, type ScreenThresholds, type SignalRule, type WrapOptions, type WrappedBatch, type WrappedEntry, capWeak, foldForMatching, normalizeInbound, parseClassification, randomDelimiter, riskOf, screenInbound, wrapForAgent, wrapRuleLine };