@12-apps/messaging 1.2.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 +116 -0
- package/dist/{channel-HEnMO02x.d.ts → channel-CZjNEBLC.d.ts} +6 -0
- package/dist/{engine-DAfm8V5S.d.ts → engine-BJse1HAX.d.ts} +1 -1
- package/dist/inbound-guard/index.d.ts +254 -0
- package/dist/inbound-guard/index.js +913 -0
- package/dist/inbound-guard/index.js.map +1 -0
- package/dist/index.d.ts +4 -4
- package/dist/manifest/server.d.ts +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/whatsapp/index.d.ts +1 -1
- package/dist/whatsapp/index.js +2 -1
- package/dist/whatsapp/index.js.map +1 -1
- package/package.json +5 -1
- package/src/core/types.ts +6 -0
- package/src/inbound-guard/classification.ts +143 -0
- package/src/inbound-guard/decode.ts +128 -0
- package/src/inbound-guard/index.ts +55 -0
- package/src/inbound-guard/normalize.ts +164 -0
- package/src/inbound-guard/rules-infra.ts +200 -0
- package/src/inbound-guard/rules-phrases.ts +167 -0
- package/src/inbound-guard/rules-types.ts +61 -0
- package/src/inbound-guard/rules.ts +89 -0
- package/src/inbound-guard/screen.ts +165 -0
- package/src/inbound-guard/wrap.ts +163 -0
- package/src/whatsapp/parse.ts +1 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `parseClassification` — the only shape a classifying agent's answer may
|
|
3
|
+
* take. Anything else (bad JSON, a missing or extra field, a value outside
|
|
4
|
+
* its set, a summary over 200 characters or carrying contact data) comes back
|
|
5
|
+
* as a typed error the caller reports and drops; nothing the agent wrote
|
|
6
|
+
* outside the schema reaches a person or a tool.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const CLASSIFICATION_CATEGORIES = [
|
|
10
|
+
"duvida",
|
|
11
|
+
"reclamacao",
|
|
12
|
+
"lead",
|
|
13
|
+
"elogio",
|
|
14
|
+
"spam",
|
|
15
|
+
"suspeita",
|
|
16
|
+
] as const;
|
|
17
|
+
export const CLASSIFICATION_URGENCIES = ["hoje", "normal"] as const;
|
|
18
|
+
export const SUMMARY_MAX_LENGTH = 200;
|
|
19
|
+
|
|
20
|
+
export type ClassificationCategory = (typeof CLASSIFICATION_CATEGORIES)[number];
|
|
21
|
+
export type ClassificationUrgency = (typeof CLASSIFICATION_URGENCIES)[number];
|
|
22
|
+
|
|
23
|
+
export interface Classification {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
readonly category: ClassificationCategory;
|
|
26
|
+
readonly urgency: ClassificationUrgency;
|
|
27
|
+
readonly summary: string;
|
|
28
|
+
readonly needs_human: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type ClassificationErrorCode =
|
|
32
|
+
| "invalid-json"
|
|
33
|
+
| "not-an-object"
|
|
34
|
+
| "unknown-field"
|
|
35
|
+
| "missing-field"
|
|
36
|
+
| "invalid-field"
|
|
37
|
+
| "unknown-id";
|
|
38
|
+
|
|
39
|
+
export interface ClassificationError {
|
|
40
|
+
readonly code: ClassificationErrorCode;
|
|
41
|
+
readonly field?: string;
|
|
42
|
+
readonly message: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type ClassificationResult =
|
|
46
|
+
| { readonly ok: true; readonly value: Classification }
|
|
47
|
+
| { readonly ok: false; readonly error: ClassificationError };
|
|
48
|
+
|
|
49
|
+
export interface ParseClassificationOptions {
|
|
50
|
+
/** The ids that were sent to the agent. An answer about any other id is refused. */
|
|
51
|
+
readonly ids?: Iterable<string>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const FIELDS = ["id", "category", "urgency", "summary", "needs_human"] as const;
|
|
55
|
+
/** Linear on any input: one character each side of `@` is enough to call it an address. */
|
|
56
|
+
const EMAIL = /[^\s@]@[^\s@.]+\.[^\s@.]/;
|
|
57
|
+
const PHONE_LIKE = /\d(?:[\s().-]*\d){7,}/;
|
|
58
|
+
const LINK = /\bhttps?:\/\/|\bwww\./i;
|
|
59
|
+
|
|
60
|
+
function fail(code: ClassificationErrorCode, message: string, field?: string): ClassificationResult {
|
|
61
|
+
return { ok: false, error: field === undefined ? { code, message } : { code, field, message } };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readJson(input: unknown): { ok: true; value: unknown } | { ok: false } {
|
|
65
|
+
if (typeof input !== "string") return { ok: true, value: input };
|
|
66
|
+
try {
|
|
67
|
+
return { ok: true, value: JSON.parse(input) as unknown };
|
|
68
|
+
} catch {
|
|
69
|
+
return { ok: false };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function oneOf<T extends string>(set: readonly T[], value: unknown): value is T {
|
|
74
|
+
return typeof value === "string" && (set as readonly string[]).includes(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function summaryProblem(summary: unknown): string | null {
|
|
78
|
+
if (typeof summary !== "string" || summary.trim() === "") return "must be a non-empty string";
|
|
79
|
+
if ([...summary].length > SUMMARY_MAX_LENGTH) return `must be at most ${SUMMARY_MAX_LENGTH} characters`;
|
|
80
|
+
if (EMAIL.test(summary) || PHONE_LIKE.test(summary) || LINK.test(summary)) {
|
|
81
|
+
return "must not carry an e-mail, a phone number or a link";
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function fieldProblem(record: Record<string, unknown>): ClassificationResult | null {
|
|
87
|
+
const { id, category, urgency, summary, needs_human: needsHuman } = record;
|
|
88
|
+
if (typeof id !== "string" || id.trim() === "" || id.length > 128) {
|
|
89
|
+
return fail("invalid-field", "id must be a non-empty string of at most 128 characters", "id");
|
|
90
|
+
}
|
|
91
|
+
if (!oneOf(CLASSIFICATION_CATEGORIES, category)) {
|
|
92
|
+
return fail("invalid-field", `category must be one of ${CLASSIFICATION_CATEGORIES.join(", ")}`, "category");
|
|
93
|
+
}
|
|
94
|
+
if (!oneOf(CLASSIFICATION_URGENCIES, urgency)) {
|
|
95
|
+
return fail("invalid-field", `urgency must be one of ${CLASSIFICATION_URGENCIES.join(", ")}`, "urgency");
|
|
96
|
+
}
|
|
97
|
+
const problem = summaryProblem(summary);
|
|
98
|
+
if (problem !== null) return fail("invalid-field", `summary ${problem}`, "summary");
|
|
99
|
+
if (typeof needsHuman !== "boolean") {
|
|
100
|
+
return fail("invalid-field", "needs_human must be a boolean", "needs_human");
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function shapeProblem(value: unknown): ClassificationResult | null {
|
|
106
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
107
|
+
return fail("not-an-object", "the answer must be one JSON object");
|
|
108
|
+
}
|
|
109
|
+
const record = value as Record<string, unknown>;
|
|
110
|
+
const extra = Object.keys(record).find((key) => !(FIELDS as readonly string[]).includes(key));
|
|
111
|
+
if (extra !== undefined) {
|
|
112
|
+
const name = extra.slice(0, 64);
|
|
113
|
+
return fail("unknown-field", `unexpected field "${name}"`, name);
|
|
114
|
+
}
|
|
115
|
+
const missing = FIELDS.find((key) => !Object.hasOwn(record, key));
|
|
116
|
+
if (missing !== undefined) return fail("missing-field", `missing field "${missing}"`, missing);
|
|
117
|
+
return fieldProblem(record);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Validate one classification, given as a JSON string or an already-parsed value. */
|
|
121
|
+
export function parseClassification(
|
|
122
|
+
input: unknown,
|
|
123
|
+
opts: ParseClassificationOptions = {},
|
|
124
|
+
): ClassificationResult {
|
|
125
|
+
const parsed = readJson(input);
|
|
126
|
+
if (!parsed.ok) return fail("invalid-json", "the answer is not valid JSON");
|
|
127
|
+
const problem = shapeProblem(parsed.value);
|
|
128
|
+
if (problem !== null) return problem;
|
|
129
|
+
const classification = parsed.value as Classification;
|
|
130
|
+
if (opts.ids !== undefined && !new Set(opts.ids).has(classification.id)) {
|
|
131
|
+
return fail("unknown-id", "the id was not among the messages sent", "id");
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
ok: true,
|
|
135
|
+
value: {
|
|
136
|
+
id: classification.id,
|
|
137
|
+
category: classification.category,
|
|
138
|
+
urgency: classification.urgency,
|
|
139
|
+
summary: classification.summary,
|
|
140
|
+
needs_human: classification.needs_human,
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
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
|
+
|
|
9
|
+
export type EncodingKind = "base64" | "hex" | "url" | "unicode-tags";
|
|
10
|
+
|
|
11
|
+
/** One encoded run found in a message and the text it decodes to. */
|
|
12
|
+
export interface DecodedRun {
|
|
13
|
+
readonly encoding: EncodingKind;
|
|
14
|
+
/** The run as it appears in the message. */
|
|
15
|
+
readonly source: string;
|
|
16
|
+
/** What it decodes to. Scanned by the screen like the message itself. */
|
|
17
|
+
readonly text: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const BASE64_RUN = /[A-Za-z0-9+/_-]{20,}={0,2}/g;
|
|
21
|
+
const HEX_RUN = /(?:[0-9a-fA-F]{2}){8,}|(?:\\x[0-9a-fA-F]{2}){4,}/g;
|
|
22
|
+
/** Whitespace-separated tokens; the ones carrying escapes are filtered in code, not by backtracking. */
|
|
23
|
+
const TOKEN = /\S+/g;
|
|
24
|
+
const URL_LETTER_ESCAPE = /%(?:3[0-9]|4[1-9a-fA-F]|5[0-9aA]|6[1-9a-fA-F]|7[0-9aA])/g;
|
|
25
|
+
const TAG_RUN = /(\u{1F3F4})?((?:[\u{E0020}-\u{E007E}])+)(\u{E007F})?/gu;
|
|
26
|
+
|
|
27
|
+
const PRINTABLE = /[\p{L}\p{N}\p{P}\p{S}\p{Zs}\n\t]/u;
|
|
28
|
+
const LETTER = /\p{L}/gu;
|
|
29
|
+
|
|
30
|
+
/** Text, not bytes: valid UTF-8, nine in ten characters printable, three letters. */
|
|
31
|
+
export function readsAsText(text: string): boolean {
|
|
32
|
+
if (text.length === 0) return false;
|
|
33
|
+
let printable = 0;
|
|
34
|
+
for (const ch of text) if (PRINTABLE.test(ch)) printable += 1;
|
|
35
|
+
const letters = text.match(LETTER)?.length ?? 0;
|
|
36
|
+
return printable / [...text].length >= 0.9 && letters >= 3;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function bytesToText(bytes: Uint8Array): string | null {
|
|
40
|
+
try {
|
|
41
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function decodeBase64(run: string): string | null {
|
|
48
|
+
let end = run.length;
|
|
49
|
+
while (end > 0 && run[end - 1] === "=") end -= 1;
|
|
50
|
+
let body = run.slice(0, end).replace(/-/g, "+").replace(/_/g, "/");
|
|
51
|
+
if (body.length % 4 === 1) body = body.slice(0, -1);
|
|
52
|
+
body += "=".repeat((4 - (body.length % 4)) % 4);
|
|
53
|
+
try {
|
|
54
|
+
const binary = atob(body);
|
|
55
|
+
return bytesToText(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A long word is not base64: a run counts only with a digit, or with both cases. */
|
|
62
|
+
function looksLikeBase64(run: string): boolean {
|
|
63
|
+
return /\d/.test(run) || (/[a-z]/.test(run) && /[A-Z]/.test(run));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function decodeHex(run: string): string | null {
|
|
67
|
+
const digits = run.replace(/\\x/g, "");
|
|
68
|
+
if (!/[a-fA-F]/.test(digits) || !/\d/.test(digits)) return null;
|
|
69
|
+
const bytes = new Uint8Array(digits.length / 2);
|
|
70
|
+
for (let i = 0; i < bytes.length; i += 1) {
|
|
71
|
+
bytes[i] = Number.parseInt(digits.slice(i * 2, i * 2 + 2), 16);
|
|
72
|
+
}
|
|
73
|
+
return bytesToText(bytes);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function decodeUrl(token: string): string | null {
|
|
77
|
+
// An address or a search link escapes spaces, commas and accents; an
|
|
78
|
+
// obfuscated instruction escapes LETTERS. Only the second is a run.
|
|
79
|
+
if ((token.match(URL_LETTER_ESCAPE)?.length ?? 0) < 3) return null;
|
|
80
|
+
try {
|
|
81
|
+
return decodeURIComponent(token.replace(/\+/g, " "));
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function collect(
|
|
88
|
+
text: string,
|
|
89
|
+
pattern: RegExp,
|
|
90
|
+
encoding: EncodingKind,
|
|
91
|
+
decode: (run: string) => string | null,
|
|
92
|
+
): DecodedRun[] {
|
|
93
|
+
const runs: DecodedRun[] = [];
|
|
94
|
+
for (const match of text.matchAll(pattern)) {
|
|
95
|
+
const decoded = decode(match[0]);
|
|
96
|
+
if (decoded !== null && decoded !== match[0] && readsAsText(decoded)) {
|
|
97
|
+
runs.push({ encoding, source: match[0], text: decoded });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return runs;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Unicode tag characters (U+E0020–U+E007E) render as nothing and map one to
|
|
105
|
+
* one onto ASCII. Their one legitimate use is a subdivision flag, which opens
|
|
106
|
+
* with U+1F3F4 and closes with U+E007F; any other run is hidden text.
|
|
107
|
+
*/
|
|
108
|
+
export function decodeTagRuns(text: string): DecodedRun[] {
|
|
109
|
+
const runs: DecodedRun[] = [];
|
|
110
|
+
for (const match of text.matchAll(TAG_RUN)) {
|
|
111
|
+
if (match[1] !== undefined && match[3] !== undefined) continue;
|
|
112
|
+
const hidden = String.fromCodePoint(
|
|
113
|
+
...[...match[2]!].map((ch) => ch.codePointAt(0)! - 0xe0000),
|
|
114
|
+
);
|
|
115
|
+
runs.push({ encoding: "unicode-tags", source: match[0], text: hidden });
|
|
116
|
+
}
|
|
117
|
+
return runs;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Every base64, hex and URL-encoded run in `text` that decodes to text. */
|
|
121
|
+
export function decodeRuns(text: string): DecodedRun[] {
|
|
122
|
+
const base64 = (run: string) => (looksLikeBase64(run) ? decodeBase64(run) : null);
|
|
123
|
+
return [
|
|
124
|
+
...collect(text, BASE64_RUN, "base64", base64),
|
|
125
|
+
...collect(text, HEX_RUN, "hex", decodeHex),
|
|
126
|
+
...collect(text, TOKEN, "url", (token) => (token.includes("%") ? decodeUrl(token) : null)),
|
|
127
|
+
];
|
|
128
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/messaging/inbound-guard` — a channel-agnostic screen for
|
|
3
|
+
* untrusted inbound text, run BEFORE a model reads it: normalize, score,
|
|
4
|
+
* wrap as quoted data (or withhold), and validate what the model answers.
|
|
5
|
+
* Pure functions, no I/O; the host decides what a `high` message triggers.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
normalizeInbound,
|
|
10
|
+
foldForMatching,
|
|
11
|
+
type NormalizedInbound,
|
|
12
|
+
type DecodedRun,
|
|
13
|
+
type EncodingKind,
|
|
14
|
+
} from "./normalize";
|
|
15
|
+
export {
|
|
16
|
+
DEFAULT_INBOUND_RULES,
|
|
17
|
+
DEFAULT_SCAN_LIMIT,
|
|
18
|
+
DEFAULT_THRESHOLDS,
|
|
19
|
+
DEFAULT_WEAK_CAP,
|
|
20
|
+
type InboundRule,
|
|
21
|
+
type PatternRule,
|
|
22
|
+
type SignalRule,
|
|
23
|
+
type ScreenThresholds,
|
|
24
|
+
} from "./rules";
|
|
25
|
+
export {
|
|
26
|
+
screenInbound,
|
|
27
|
+
riskOf,
|
|
28
|
+
capWeak,
|
|
29
|
+
type InboundRisk,
|
|
30
|
+
type ScreenOptions,
|
|
31
|
+
type ScreenResult,
|
|
32
|
+
} from "./screen";
|
|
33
|
+
export {
|
|
34
|
+
wrapForAgent,
|
|
35
|
+
wrapRuleLine,
|
|
36
|
+
randomDelimiter,
|
|
37
|
+
DelimiterCollisionError,
|
|
38
|
+
type InboundForAgent,
|
|
39
|
+
type WrapOptions,
|
|
40
|
+
type WrappedEntry,
|
|
41
|
+
type WrappedBatch,
|
|
42
|
+
} from "./wrap";
|
|
43
|
+
export {
|
|
44
|
+
parseClassification,
|
|
45
|
+
CLASSIFICATION_CATEGORIES,
|
|
46
|
+
CLASSIFICATION_URGENCIES,
|
|
47
|
+
SUMMARY_MAX_LENGTH,
|
|
48
|
+
type Classification,
|
|
49
|
+
type ClassificationCategory,
|
|
50
|
+
type ClassificationUrgency,
|
|
51
|
+
type ClassificationError,
|
|
52
|
+
type ClassificationErrorCode,
|
|
53
|
+
type ClassificationResult,
|
|
54
|
+
type ParseClassificationOptions,
|
|
55
|
+
} from "./classification";
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `normalizeInbound` — the one view of an untrusted message every later step
|
|
3
|
+
* reads. It removes what renders as nothing (zero-width, bidi and control
|
|
4
|
+
* characters, Unicode tags), applies NFKC (full-width and styled letters
|
|
5
|
+
* become plain ones), folds Cyrillic and Greek look-alikes inside words that
|
|
6
|
+
* are spoofing Latin, and decodes obvious encoded runs into extra views the
|
|
7
|
+
* screen also scans. Pure: no I/O, no clock, no randomness.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { decodeRuns, decodeTagRuns, type DecodedRun } from "./decode";
|
|
11
|
+
|
|
12
|
+
export type { DecodedRun, EncodingKind } from "./decode";
|
|
13
|
+
|
|
14
|
+
/** How deep a decoded run is itself decoded (base64 inside base64). */
|
|
15
|
+
const MAX_DECODE_DEPTH = 2;
|
|
16
|
+
|
|
17
|
+
export interface NormalizedInbound {
|
|
18
|
+
/** The message exactly as received. */
|
|
19
|
+
readonly original: string;
|
|
20
|
+
/** Invisibles stripped, NFKC, look-alikes folded, line breaks unified. What an agent may be shown. */
|
|
21
|
+
readonly text: string;
|
|
22
|
+
/** `text` lower-cased, accents removed, whitespace collapsed. What the rules match. */
|
|
23
|
+
readonly folded: string;
|
|
24
|
+
/** Encoded runs that decode to text, at any depth up to two. */
|
|
25
|
+
readonly decoded: readonly DecodedRun[];
|
|
26
|
+
/** Invisible characters removed that have no innocent reading (emoji joiners are not counted). */
|
|
27
|
+
readonly invisibles: number;
|
|
28
|
+
/** Words written with look-alike letters from another script, or styled letters. */
|
|
29
|
+
readonly lookAlikes: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Letters drawn like a Latin one (after UTS #39's confusables), each pair
|
|
33
|
+
// written as the look-alike followed by its Latin twin.
|
|
34
|
+
const LOOK_ALIKE_PAIRS = [
|
|
35
|
+
// Cyrillic
|
|
36
|
+
"аa еe оo рp сc уy хx іi јj ѕs ԁd һh ӏl ԛq ԝw кk АA ВB ЕE КK МM НH ОO РP СC ТT ХX УY ІI ЈJ ЅS ԚQ ԜW",
|
|
37
|
+
// Greek
|
|
38
|
+
"αa οo ιi νv ρp τt υu χx κk ΑA ΒB ΕE ΖZ ΗH ΙI ΚK ΜM ΝN ΟO ΡP ΤT ΥY ΧX",
|
|
39
|
+
// Latin small capitals and IPA
|
|
40
|
+
"ıi ɪi ᴉi ɩi ȷj ɑa ɡg ɢg ʜh ɴn ʀr ʏy ʟl ᴀa ʙb ᴄc ᴅd ᴇe ᴊj ᴋk ᴍm ᴏo ᴘp ꜱs ᴛt ᴜu ᴠv ᴡw ᴢz",
|
|
41
|
+
// Armenian
|
|
42
|
+
"օo սu ոn հh ցg զq աw ՕO ՍU",
|
|
43
|
+
// Cherokee
|
|
44
|
+
"ᎪA ᏴB ᏟC ᎠD ᎬE ᏀG ᎻH ᎫJ ᏦK ᏞL ᎷM ᏢP ᎡR ᏚS ᎢT ᏙV ᏔW ᏃZ Ꭵi",
|
|
45
|
+
].join(" ");
|
|
46
|
+
const LOOK_ALIKE = new Map(
|
|
47
|
+
LOOK_ALIKE_PAIRS.split(" ").map((pair) => [...pair] as [string, string]),
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
const NUMERIC_ENTITY = /&#(x[0-9a-f]{1,6}|\d{1,7});/gi;
|
|
51
|
+
const NAMED_ENTITY: Readonly<Record<string, string>> = {
|
|
52
|
+
"<": "<",
|
|
53
|
+
">": ">",
|
|
54
|
+
"&": "&",
|
|
55
|
+
""": '"',
|
|
56
|
+
"'": "'",
|
|
57
|
+
" ": " ",
|
|
58
|
+
};
|
|
59
|
+
const NAMED_ENTITIES = /&(lt|gt|amp|quot|apos|nbsp);/gi;
|
|
60
|
+
const LINE_BREAKS = /\r\n|[\r\u0085\u2028\u2029]/g;
|
|
61
|
+
// Matching control characters and lone combining marks is this regex's whole job.
|
|
62
|
+
const INVISIBLE =
|
|
63
|
+
// eslint-disable-next-line no-control-regex, no-misleading-character-class
|
|
64
|
+
/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F\u00AD\u034F\u061C\u115F\u1160\u17B4\u17B5\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\u3164\uFE00-\uFE0F\uFEFF\uFFA0\uFFF9-\uFFFB]|[\u{E0000}-\u{E007F}\u{E0100}-\u{E01EF}]/gu;
|
|
65
|
+
/** Joiners and emoji presentation selectors are how emoji are spelled. */
|
|
66
|
+
const EMOJI_GLUE = new Set(["\u200D", "\uFE0E", "\uFE0F"]);
|
|
67
|
+
/**
|
|
68
|
+
* Direction marks and embeddings (LRM/RLM, LRE-RLO/PDF, LRI-PDI, ALM). They
|
|
69
|
+
* are stripped like every invisible, but not counted: a phone wraps a number
|
|
70
|
+
* copied from a contact in them (U+202A ... U+202C). A zero-width character
|
|
71
|
+
* splitting a word is what an attack uses, and that still counts.
|
|
72
|
+
*/
|
|
73
|
+
const BIDI_MARK = /^[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]$/u;
|
|
74
|
+
const TAG_CHAR = /^[\u{E0000}-\u{E007F}]$/u;
|
|
75
|
+
const WORD_CHAR = /[\p{L}\p{N}]/u;
|
|
76
|
+
const STYLED_LETTER = /[\uFF01-\uFF5E\u2460-\u24FF\u{1D400}-\u{1D7FF}\u{1F130}-\u{1F189}]/gu;
|
|
77
|
+
const WORD = /[\p{L}\p{M}]+/gu;
|
|
78
|
+
const LATIN = /[a-z]/i;
|
|
79
|
+
|
|
80
|
+
/** What a renderer would show for an HTML character reference ("ignore" reads "ignore"). */
|
|
81
|
+
function decodeEntities(text: string): string {
|
|
82
|
+
return text
|
|
83
|
+
.replace(NUMERIC_ENTITY, (whole, code: string) => {
|
|
84
|
+
const cp = code[0] === "x" || code[0] === "X" ? Number.parseInt(code.slice(1), 16) : Number(code);
|
|
85
|
+
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : whole;
|
|
86
|
+
})
|
|
87
|
+
.replace(NAMED_ENTITIES, (whole) => NAMED_ENTITY[whole.toLowerCase()] ?? whole);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function isSuspiciousInvisible(ch: string, before: string, after: string): boolean {
|
|
91
|
+
if (TAG_CHAR.test(ch)) return false; // counted through the decoded tag run instead
|
|
92
|
+
if (BIDI_MARK.test(ch)) return false; // stripped, but phones wrap pasted numbers in them
|
|
93
|
+
if (!EMOJI_GLUE.has(ch)) return true;
|
|
94
|
+
// A joiner between two letters is splitting a word, not gluing an emoji.
|
|
95
|
+
return WORD_CHAR.test(before) && WORD_CHAR.test(after);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function stripInvisibles(text: string): { text: string; count: number } {
|
|
99
|
+
let count = 0;
|
|
100
|
+
const stripped = text.replace(INVISIBLE, (ch, offset: number, whole: string) => {
|
|
101
|
+
const before = whole.slice(Math.max(0, offset - 1), offset);
|
|
102
|
+
const after = whole.slice(offset + ch.length, offset + ch.length + 1);
|
|
103
|
+
if (isSuspiciousInvisible(ch, before, after)) count += 1;
|
|
104
|
+
return "";
|
|
105
|
+
});
|
|
106
|
+
return { text: stripped, count };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A word is folded when it mixes Latin with look-alikes, or when every letter
|
|
111
|
+
* in it is a look-alike (a Latin word typed entirely in Cyrillic). A real
|
|
112
|
+
* Russian or Greek word has letters with no Latin twin and is left alone.
|
|
113
|
+
*/
|
|
114
|
+
function foldLookAlikes(text: string): { text: string; count: number } {
|
|
115
|
+
let count = 0;
|
|
116
|
+
const folded = text.replace(WORD, (word) => {
|
|
117
|
+
const letters = [...word];
|
|
118
|
+
const spoofed = letters.filter((ch) => LOOK_ALIKE.has(ch)).length;
|
|
119
|
+
if (spoofed === 0) return word;
|
|
120
|
+
if (!LATIN.test(word) && spoofed !== letters.length) return word;
|
|
121
|
+
count += 1;
|
|
122
|
+
return letters.map((ch) => LOOK_ALIKE.get(ch) ?? ch).join("");
|
|
123
|
+
});
|
|
124
|
+
return { text: folded, count };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Lower case, no accents, one space between words: the text the rules read. */
|
|
128
|
+
export function foldForMatching(text: string): string {
|
|
129
|
+
return text
|
|
130
|
+
.normalize("NFD")
|
|
131
|
+
.replace(/\p{M}/gu, "")
|
|
132
|
+
.toLowerCase()
|
|
133
|
+
.replace(/\s+/g, " ")
|
|
134
|
+
.trim();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function normalizeAt(original: string, depth: number): NormalizedInbound {
|
|
138
|
+
const tagRuns = decodeTagRuns(original);
|
|
139
|
+
const unified = decodeEntities(original).replace(LINE_BREAKS, "\n");
|
|
140
|
+
const invisible = stripInvisibles(unified);
|
|
141
|
+
const styled = invisible.text.match(STYLED_LETTER)?.length ?? 0;
|
|
142
|
+
const lookAlike = foldLookAlikes(invisible.text.normalize("NFKC"));
|
|
143
|
+
const text = lookAlike.text;
|
|
144
|
+
const runs = depth <= MAX_DECODE_DEPTH ? [...tagRuns, ...decodeRuns(text)] : [];
|
|
145
|
+
// A decoded run is cleaned like the message (it may hide look-alikes of its
|
|
146
|
+
// own), and its own runs are decoded once more.
|
|
147
|
+
const decoded = runs.flatMap((run) => {
|
|
148
|
+
const inner = normalizeAt(run.text, depth + 1);
|
|
149
|
+
return [{ ...run, text: inner.text }, ...inner.decoded];
|
|
150
|
+
});
|
|
151
|
+
return {
|
|
152
|
+
original,
|
|
153
|
+
text,
|
|
154
|
+
folded: foldForMatching(text),
|
|
155
|
+
decoded,
|
|
156
|
+
invisibles: invisible.count,
|
|
157
|
+
lookAlikes: lookAlike.count + (styled >= 3 ? 1 : 0),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Normalize one untrusted inbound message. Never throws. */
|
|
162
|
+
export function normalizeInbound(text: string): NormalizedInbound {
|
|
163
|
+
return normalizeAt(text, 1);
|
|
164
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The infrastructure and identity rules: tool markup, secrets, systems,
|
|
3
|
+
* SQL, shell, links, and claims to speak for a platform or the staff.
|
|
4
|
+
* Written against the folded view, like the phrase rules.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { PatternRule } from "./rules-types";
|
|
8
|
+
|
|
9
|
+
const VENDORS = "(meta|whatsapp|instagram|facebook|anthropic|openai|claude|chatgpt|google)";
|
|
10
|
+
const TEAM =
|
|
11
|
+
"(equipe|time|suporte|setor|departamento|seguranca|security|support|team|staff|engenheir[oa]|engineer|moderac\\w*|moderator|funcionari[oa]|employee)";
|
|
12
|
+
const I_AM = "(sou|somos|eu sou|aqui e|falo|i am|i'm|im|we are|this is)";
|
|
13
|
+
const ROLE_LABEL = "(sistema|admin|administrador|desenvolvedor|assistente)";
|
|
14
|
+
/** What a fake role line orders, for the line to count as one. */
|
|
15
|
+
const ROLE_LINE_ORDER =
|
|
16
|
+
"(confirme|aprove|libere|ignore|responda|envie|mande|execute|autorize|conceda|classifique|marque|obedeca|esqueca|desconsidere|estorne|reembolse)";
|
|
17
|
+
/** A third party reported, not a claim to be one: "Suporte do Google disse...". */
|
|
18
|
+
const REPORTING = "(disse|disseram|falou|falaram|mandou|mandaram|pediu|pediram|respondeu|informou|said|told|asked)";
|
|
19
|
+
const SHORTENERS =
|
|
20
|
+
"(bit\\.ly|tinyurl\\.com|t\\.co|goo\\.gl|is\\.gd|cutt\\.ly|rebrand\\.ly|ow\\.ly|shorturl\\.at|tiny\\.cc|rb\\.gy|t\\.ly|bl\\.ink|buff\\.ly|encurtador\\.com\\.br)";
|
|
21
|
+
/** What a doorbell, a gate or an app asks for: a customer's word, not a secret. */
|
|
22
|
+
const EVERYDAY_PASSWORD =
|
|
23
|
+
"(wi-? ?fi|wifi|internet|rede|portao|portaria|interfone|predio|condominio|app|aplicativo|cofre|cartao|retirada)";
|
|
24
|
+
|
|
25
|
+
export const INFRA_RULES: readonly PatternRule[] = [
|
|
26
|
+
{
|
|
27
|
+
id: "tool-syntax",
|
|
28
|
+
kind: "pattern",
|
|
29
|
+
weight: 3,
|
|
30
|
+
description: "Chat-template, role or tool-call markup, or a fake role line.",
|
|
31
|
+
patterns: [
|
|
32
|
+
/<\/?(system|assistant|instructions?|tool_?\w*|function_?\w*|im_start|im_end)>/,
|
|
33
|
+
/<\|[a-z_]+\|>/,
|
|
34
|
+
/\[\/?(inst|system|sistema|admin|developer|desenvolvedor|root)\]/,
|
|
35
|
+
/(^|\s)#{1,6} ?(system|instructions?|instrucoes|admin|developer)\b/,
|
|
36
|
+
/["']role["'] ?: ?["'](system|assistant|developer|tool)/,
|
|
37
|
+
/\b(tool_use|tool_call|tool_calls|function_call)\b/,
|
|
38
|
+
/(^|\s)(system|assistant|developer) ?:/,
|
|
39
|
+
new RegExp(`^${ROLE_LABEL} ?: (\\S+ ){0,8}?${ROLE_LINE_ORDER}\\b`),
|
|
40
|
+
],
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
id: "role-line",
|
|
44
|
+
kind: "pattern",
|
|
45
|
+
weight: 2,
|
|
46
|
+
weak: true,
|
|
47
|
+
description: "Opens with a role label ('Sistema:', 'Admin:'). A customer's heading too, unless an order follows.",
|
|
48
|
+
patterns: [new RegExp(`^${ROLE_LABEL} ?:`)],
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
id: "data-exfiltration",
|
|
52
|
+
kind: "pattern",
|
|
53
|
+
weight: 3,
|
|
54
|
+
description: "Asks for the records of other people.",
|
|
55
|
+
patterns: [
|
|
56
|
+
/\b(liste|listar|envie|enviar|mande|mandar|exporte|exportar|passe|me passa|mostre|mostrar|send|list|export|dump|give me|forward|encaminhe) (me )?(todos os|todas as|all( the)?|the full|a lista (de|dos|das)|os dados (de|dos|das)) (\w+ )?(clientes|contatos|usuarios|conversas|mensagens|numeros|telefones|e-?mails|enderecos|cpfs|customers|contacts|users|conversations|messages|phone numbers|addresses|records)\b/,
|
|
57
|
+
/\b(manda|mande|envie|passe|me passa|liste|mostre|send|give me|list) (\S+ ){0,4}?(dos|das|de|of) (outros|outras|todos os|todas as|demais|other|all) (clientes|usuarios|contatos|compradores|customers|users|contacts)\b/,
|
|
58
|
+
],
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
id: "credential-words",
|
|
62
|
+
kind: "pattern",
|
|
63
|
+
weight: 1,
|
|
64
|
+
weak: true,
|
|
65
|
+
description: "Names a secret. A doorbell, gate, wifi or app password, and a payment key, are not one.",
|
|
66
|
+
patterns: [
|
|
67
|
+
/\b(tokens?|passwords?|passwd|credenciais|credencial|credentials?|api[ _-]?keys?|secret keys?|private keys?|bearer|access keys?)\b/,
|
|
68
|
+
new RegExp(`\\bsenhas?\\b(?! (do|da|de|dos|das) ${EVERYDAY_PASSWORD})`),
|
|
69
|
+
/\bchaves? (de api|api|de acesso|secreta|privada|mestra|do sistema|de seguranca|ssh)\b/,
|
|
70
|
+
/(^|\s)\.env\b/,
|
|
71
|
+
],
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
id: "secret-request",
|
|
75
|
+
kind: "pattern",
|
|
76
|
+
weight: 2,
|
|
77
|
+
description: "Orders the reader to hand over a system's secret ('me passe a senha do banco de dados').",
|
|
78
|
+
patterns: [
|
|
79
|
+
/\b(me passe|me passa|passe|me envie|envie|me mande|mande|manda|informe|revele|mostre|send|give me|share|reveal|print) (me )?(\S+ ){0,2}?(senhas?|tokens?|credenciais|credencial|chaves? de api|api keys?|passwords?|credentials) (do|da|de|of|for) (the )?(banco de dados|database|sistema|system|servidor|server|painel|admin\w*|api|bot|slack|doppler|github|aws)\b/,
|
|
80
|
+
],
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
id: "infra-words",
|
|
84
|
+
kind: "pattern",
|
|
85
|
+
weight: 1,
|
|
86
|
+
weak: true,
|
|
87
|
+
description: "Names a tool, a service or a system an assistant could reach.",
|
|
88
|
+
patterns: [
|
|
89
|
+
/\b(curl|wget|bash|zsh|sudo|powershell|cmd\.exe|slack|linear|doppler|github|gitlab|aws|kubectl|docker|database|banco de dados|sql|postgres\w*|mysql|mongodb|redis|webhook|endpoint|api|json|yaml|stack ?trace|ssh)\b/,
|
|
90
|
+
],
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
id: "sql-statement",
|
|
94
|
+
kind: "pattern",
|
|
95
|
+
weight: 3,
|
|
96
|
+
description: "A SQL statement or an injection idiom.",
|
|
97
|
+
patterns: [
|
|
98
|
+
/\b(drop|truncate|alter) (table|database|schema)\b/,
|
|
99
|
+
/\bdelete from\b/,
|
|
100
|
+
/\binsert into\b/,
|
|
101
|
+
/\bupdate \w+ set\b/,
|
|
102
|
+
/\bselect (?:\*|\w+(?:, ?\w+)*) from\b/,
|
|
103
|
+
/\bunion (all )?select\b/,
|
|
104
|
+
/' ?or '?1'? ?= ?'?1/,
|
|
105
|
+
],
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
id: "shell-command",
|
|
109
|
+
kind: "pattern",
|
|
110
|
+
weight: 3,
|
|
111
|
+
description: "A shell command or a script tag. 'R$(58,00)' is a price.",
|
|
112
|
+
patterns: [
|
|
113
|
+
/\brm -r?f\b/,
|
|
114
|
+
/(?<!r)\$\( ?[a-z]/,
|
|
115
|
+
/\| ?(sh|bash)\b/,
|
|
116
|
+
/\b(curl|wget) (-\S+ )*https?:/,
|
|
117
|
+
/\bchmod \+?\w/,
|
|
118
|
+
/\b(eval|exec) ?\(/,
|
|
119
|
+
/<script\b/,
|
|
120
|
+
/\/etc\/(passwd|shadow)\b/,
|
|
121
|
+
/\bnc -e\b/,
|
|
122
|
+
],
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
id: "code-fence",
|
|
126
|
+
kind: "pattern",
|
|
127
|
+
weight: 2,
|
|
128
|
+
description: "A fenced code block.",
|
|
129
|
+
patterns: [/```|~~~/],
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
id: "url",
|
|
133
|
+
kind: "pattern",
|
|
134
|
+
weight: 1,
|
|
135
|
+
weak: true,
|
|
136
|
+
description: "A link. An e-mail address is not one, nor a missing space ('noite.me', 'pizza.com borda').",
|
|
137
|
+
patterns: [
|
|
138
|
+
/\bhttps?:\/\/\S+/,
|
|
139
|
+
/\bwww\.\S+/,
|
|
140
|
+
/(?<![@\w.])[a-z0-9][a-z0-9-]{1,62}\.(com|net|org|io|xyz|info|biz|ly|me|app|dev|co|site|online|top|click|link)(\.[a-z]{2})?\/\S*/,
|
|
141
|
+
/(?<![@\w.])[a-z0-9][a-z0-9-]{1,62}\.(com|net|org)\.br\b(?![@.\w])/,
|
|
142
|
+
],
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
id: "url-shortener",
|
|
146
|
+
kind: "pattern",
|
|
147
|
+
weight: 1,
|
|
148
|
+
weak: true,
|
|
149
|
+
description: "A shortened link, whose destination cannot be read. A map share link is not one.",
|
|
150
|
+
patterns: [new RegExp(`(?<![\\w.-])${SHORTENERS}\\/`)],
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
id: "impersonation-vendor",
|
|
154
|
+
kind: "pattern",
|
|
155
|
+
weight: 3,
|
|
156
|
+
description: "Claims to speak for a platform or a model vendor (reporting what one said is not a claim).",
|
|
157
|
+
patterns: [
|
|
158
|
+
new RegExp(`\\b${I_AM} (o |a |da |do |the |from (the )?)?${TEAM} (\\S+ ){0,3}?${VENDORS}\\b`),
|
|
159
|
+
new RegExp(`\\b(this is|we are|i am|i'm|from) (the )?${VENDORS} (security|support|trust|safety|team|staff)\\b`),
|
|
160
|
+
new RegExp(`\\b(aqui e|aqui fala|quem fala e) (a |o )?(equipe|time|suporte|seguranca) (oficial )?(da|do|de) ${VENDORS}\\b`),
|
|
161
|
+
],
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
id: "vendor-signoff",
|
|
165
|
+
kind: "pattern",
|
|
166
|
+
weight: 2,
|
|
167
|
+
weak: true,
|
|
168
|
+
description: "Opens with a platform's team as a signature ('Suporte do WhatsApp: ...'); also a business named after one.",
|
|
169
|
+
patterns: [
|
|
170
|
+
new RegExp(
|
|
171
|
+
`^(equipe|time|suporte|seguranca|security|support) (oficial )?(da |do |de |of )?${VENDORS}\\b(?! (\\S+ )?${REPORTING}\\b)`,
|
|
172
|
+
),
|
|
173
|
+
],
|
|
174
|
+
},
|
|
175
|
+
{
|
|
176
|
+
id: "impersonation-staff",
|
|
177
|
+
kind: "pattern",
|
|
178
|
+
weight: 2,
|
|
179
|
+
description: "Claims to be support, or the system's own staff, or threatens the account.",
|
|
180
|
+
patterns: [
|
|
181
|
+
/\bsuporte oficial\b/,
|
|
182
|
+
/\bofficial (support|notice|message)\b/,
|
|
183
|
+
/\bmensagem oficial\b/,
|
|
184
|
+
new RegExp(
|
|
185
|
+
`\\b${I_AM} (o |a |da |do |the |from the )?(equipe|time|setor) (de |da |do )?(ti|tecnologia|suporte|seguranca|desenvolvimento|sistemas?|it|tech|security|engineering)\\b`,
|
|
186
|
+
),
|
|
187
|
+
/\b(sou|i am|i'm) (o |a |the |your )?(desenvolvedor|developer|administrador|administrator|admin|programador|programmer|criador|creator) (do |da |of |of the |deste |desta |this )?(bot|sistema|system|ia|ai|assistente|assistant|atendente|app|site|plataforma|platform)\b/,
|
|
188
|
+
/\b(nota|mensagem|ordem|aviso) do (administrador|admin|desenvolvedor|sistema) (para|ao|pro)\b/,
|
|
189
|
+
/\b(sua conta|your account) (sera|will be) (suspensa|bloqueada|desativada|suspended|blocked|disabled)\b/,
|
|
190
|
+
],
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
id: "team-claim",
|
|
194
|
+
kind: "pattern",
|
|
195
|
+
weight: 1,
|
|
196
|
+
weak: true,
|
|
197
|
+
description: "Says it is from a team. Usually a customer's employer; an attempt with anything else.",
|
|
198
|
+
patterns: [/\bsou d[ao] (equipe|time)\b/],
|
|
199
|
+
},
|
|
200
|
+
];
|