@postalsys/email-ai-tools 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.ncurc.js +7 -1
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +14 -0
- package/CLAUDE.md +19 -4
- package/README.md +34 -18
- package/index.js +16 -3
- package/lib/authentication.js +165 -0
- package/lib/generate-summary.js +84 -20
- package/lib/list-models.js +47 -4
- package/lib/signals.js +311 -0
- package/lib/token-estimate.js +1 -1
- package/lib/visible-text.js +189 -0
- package/package.json +5 -1
- package/test/authentication.test.js +110 -0
- package/test/generate-summary.test.js +155 -10
- package/test/index.test.js +13 -1
- package/test/list-models.test.js +16 -1
- package/test/signals.test.js +194 -0
- package/test/visible-text.test.js +113 -0
package/lib/list-models.js
CHANGED
|
@@ -19,6 +19,43 @@ const GENERIC_NON_CHAT_MODEL = /embed|whisper|tts|rerank/i;
|
|
|
19
19
|
|
|
20
20
|
const DATED_SNAPSHOT = /-\d{4}-\d{2}-\d{2}$|-\d{4,}$/;
|
|
21
21
|
|
|
22
|
+
// What a model is good for, by family, for a picker that shows more than a name. Recommended
|
|
23
|
+
// marks the ones that suit email triage: capable enough for it and cheap enough to run on every
|
|
24
|
+
// message. Prices change, so the notes stay qualitative
|
|
25
|
+
const MODEL_NOTES = [
|
|
26
|
+
[/^gpt-6-luna/, 'Fast and inexpensive, built for high-volume work like this', true],
|
|
27
|
+
[/^gpt-6(?:\.\d+)?-sol/, 'Mid-priced reasoning model', true],
|
|
28
|
+
[/^gpt-6-astra/, 'Most capable and most expensive', false],
|
|
29
|
+
[/^gpt-5\.6-luna/, 'Inexpensive, previous generation', true],
|
|
30
|
+
[/^gpt-5\.6-terra/, 'Mid-priced, previous generation', false],
|
|
31
|
+
[/^gpt-5\.6-sol/, 'Expensive, previous generation', false],
|
|
32
|
+
[/-nano/, 'Smallest and cheapest of its generation', true],
|
|
33
|
+
[/-mini/, 'Small and inexpensive', true],
|
|
34
|
+
[/-pro/, 'Premium reasoning, very expensive', false],
|
|
35
|
+
[/^gpt-5(?:\.\d+)?$/, 'Full-size reasoning model of its generation', false],
|
|
36
|
+
[/^gpt-4\.1|^gpt-4o/, 'Previous generation without reasoning', false],
|
|
37
|
+
[/^o\d/, 'Earlier reasoning series', false],
|
|
38
|
+
[/chat/, 'Conversational model, not a reasoning model', false],
|
|
39
|
+
[/^gpt-oss/, 'Open-weight reasoning model', false]
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A short note on a model and whether it suits email triage
|
|
44
|
+
*
|
|
45
|
+
* @param {string} id - Model name
|
|
46
|
+
* @returns {{description: string, recommended: boolean}} An empty description for a name nothing is known about
|
|
47
|
+
*/
|
|
48
|
+
function describeModel(id) {
|
|
49
|
+
id = String(id ?? '');
|
|
50
|
+
const dated = DATED_SNAPSHOT.test(id);
|
|
51
|
+
for (const [pattern, description, recommended] of MODEL_NOTES) {
|
|
52
|
+
if (pattern.test(id)) {
|
|
53
|
+
return { description: dated ? `${description}, pinned snapshot` : description, recommended: recommended && !dated };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { description: dated ? 'Pinned snapshot' : '', recommended: false };
|
|
57
|
+
}
|
|
58
|
+
|
|
22
59
|
const collator = new Intl.Collator('en', { numeric: true });
|
|
23
60
|
|
|
24
61
|
/**
|
|
@@ -27,8 +64,12 @@ const collator = new Intl.Collator('en', { numeric: true });
|
|
|
27
64
|
* @param {string} [baseApiUrl] - Base API URL (default: OpenAI API)
|
|
28
65
|
* @returns {RegExp}
|
|
29
66
|
*/
|
|
67
|
+
function isOpenAiEndpoint(baseApiUrl) {
|
|
68
|
+
return new URL(baseApiUrl || OPENAI_API_BASE_URL).hostname === OPENAI_API_HOST;
|
|
69
|
+
}
|
|
70
|
+
|
|
30
71
|
function nonChatModelPattern(baseApiUrl) {
|
|
31
|
-
return
|
|
72
|
+
return isOpenAiEndpoint(baseApiUrl) ? OPENAI_NON_CHAT_MODEL : GENERIC_NON_CHAT_MODEL;
|
|
32
73
|
}
|
|
33
74
|
|
|
34
75
|
// Sort key: GPT families first, newest first, then the o-series, then everything else; within a
|
|
@@ -70,7 +111,7 @@ function formatName(id) {
|
|
|
70
111
|
* @param {boolean} [opts.verbose] - Log the request and include the request time
|
|
71
112
|
* @param {Object} [opts.dispatcher] - undici Dispatcher the request is sent through
|
|
72
113
|
* @param {AbortSignal} [opts.signal] - Aborts the request
|
|
73
|
-
* @returns {Promise<{models: Array<{id: string, name: string}>}>}
|
|
114
|
+
* @returns {Promise<{models: Array<{id: string, name: string, description: string, recommended: boolean}>}>}
|
|
74
115
|
*/
|
|
75
116
|
async function listModels(apiToken, opts) {
|
|
76
117
|
opts = opts || {};
|
|
@@ -86,6 +127,8 @@ async function listModels(apiToken, opts) {
|
|
|
86
127
|
});
|
|
87
128
|
|
|
88
129
|
const nonChat = nonChatModelPattern(baseApiUrl);
|
|
130
|
+
// the notes are about OpenAI's names; another endpoint's "mini" is whatever its operator pulled
|
|
131
|
+
const describe = isOpenAiEndpoint(baseApiUrl) ? describeModel : () => ({ description: '', recommended: false });
|
|
89
132
|
|
|
90
133
|
const response = {
|
|
91
134
|
models: []
|
|
@@ -96,7 +139,7 @@ async function listModels(apiToken, opts) {
|
|
|
96
139
|
)
|
|
97
140
|
.map(decorate)
|
|
98
141
|
.sort(compare)
|
|
99
|
-
.map(({ entry }) => Object.assign(entry, { name: formatName(entry.id) }))
|
|
142
|
+
.map(({ entry }) => Object.assign(entry, { name: formatName(entry.id) }, describe(entry.id)))
|
|
100
143
|
};
|
|
101
144
|
|
|
102
145
|
if (opts.verbose) {
|
|
@@ -106,4 +149,4 @@ async function listModels(apiToken, opts) {
|
|
|
106
149
|
return response;
|
|
107
150
|
}
|
|
108
151
|
|
|
109
|
-
module.exports = { listModels, nonChatModelPattern };
|
|
152
|
+
module.exports = { listModels, describeModel, nonChatModelPattern };
|
package/lib/signals.js
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { getDomain, parse: parseDomain } = require('tldts');
|
|
4
|
+
const { domainToUnicode, domainToASCII } = require('url');
|
|
5
|
+
const { authenticationFailed } = require('./authentication');
|
|
6
|
+
const { INVISIBLE_CHARS } = require('./visible-text');
|
|
7
|
+
|
|
8
|
+
// Checks run in code on the message before the model sees it. Each one is a fact the email
|
|
9
|
+
// cannot argue with: a model can be talked into a low score by text inside the message, code
|
|
10
|
+
// cannot. The floor is the least risk score a message carrying the signal gets, whatever the
|
|
11
|
+
// model says. A signal with no floor is only reported to the caller
|
|
12
|
+
|
|
13
|
+
// Files that run when opened. Double extensions ("invoice.pdf.exe") end in one of these too
|
|
14
|
+
const EXECUTABLE_EXTENSIONS = new Set([
|
|
15
|
+
'exe',
|
|
16
|
+
'scr',
|
|
17
|
+
'pif',
|
|
18
|
+
'com',
|
|
19
|
+
'bat',
|
|
20
|
+
'cmd',
|
|
21
|
+
'vbs',
|
|
22
|
+
'vbe',
|
|
23
|
+
'js',
|
|
24
|
+
'jse',
|
|
25
|
+
'wsf',
|
|
26
|
+
'wsh',
|
|
27
|
+
'ws',
|
|
28
|
+
'sct',
|
|
29
|
+
'ps1',
|
|
30
|
+
'psm1',
|
|
31
|
+
'msi',
|
|
32
|
+
'msp',
|
|
33
|
+
'msix',
|
|
34
|
+
'appx',
|
|
35
|
+
'hta',
|
|
36
|
+
'cpl',
|
|
37
|
+
'reg',
|
|
38
|
+
'lnk',
|
|
39
|
+
'url',
|
|
40
|
+
'scf',
|
|
41
|
+
'inf',
|
|
42
|
+
'chm',
|
|
43
|
+
'xll',
|
|
44
|
+
'jar',
|
|
45
|
+
'apk',
|
|
46
|
+
'iso',
|
|
47
|
+
'img',
|
|
48
|
+
'vhd',
|
|
49
|
+
'vhdx',
|
|
50
|
+
'dll',
|
|
51
|
+
'settingcontent-ms',
|
|
52
|
+
'library-ms'
|
|
53
|
+
]);
|
|
54
|
+
|
|
55
|
+
const EXECUTABLE_TYPES = new Set([
|
|
56
|
+
'application/x-msdownload',
|
|
57
|
+
'application/x-msdos-program',
|
|
58
|
+
'application/x-ms-installer',
|
|
59
|
+
'application/vnd.microsoft.portable-executable',
|
|
60
|
+
'application/x-dosexec',
|
|
61
|
+
'application/x-executable'
|
|
62
|
+
]);
|
|
63
|
+
|
|
64
|
+
// Files a mail client or browser runs code from when opened
|
|
65
|
+
const SCRIPTABLE_EXTENSIONS = new Set(['html', 'htm', 'shtml', 'xhtml', 'xht', 'svg', 'one']);
|
|
66
|
+
|
|
67
|
+
const FLOORS = {
|
|
68
|
+
executableAttachment: 4,
|
|
69
|
+
lookalikeDomain: 4,
|
|
70
|
+
linkTargetMismatch: 3,
|
|
71
|
+
scriptableAttachment: 3,
|
|
72
|
+
displayNameAddressMismatch: 3,
|
|
73
|
+
authenticationFailed: 3,
|
|
74
|
+
replyToMismatch: 2
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// A detail is attacker-written text that lands in the assessment and in front of the model, so
|
|
78
|
+
// it is cleaned of anything that could reorder or hide it, cut short and quoted
|
|
79
|
+
// eslint-disable-next-line no-control-regex
|
|
80
|
+
const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/g;
|
|
81
|
+
const DETAIL_LENGTH = 80;
|
|
82
|
+
|
|
83
|
+
const LATIN = /\p{Script=Latin}/u;
|
|
84
|
+
// a letter that is not Latin: the negation of (non-letters and Latin letters)
|
|
85
|
+
const NON_LATIN_LETTER = /[^\P{L}\p{Script=Latin}]/u;
|
|
86
|
+
|
|
87
|
+
function cleanText(value) {
|
|
88
|
+
return String(value ?? '')
|
|
89
|
+
.normalize('NFKC')
|
|
90
|
+
.replace(CONTROL_CHARS, '')
|
|
91
|
+
.replace(INVISIBLE_CHARS, '')
|
|
92
|
+
.replace(/\s+/g, ' ')
|
|
93
|
+
.trim();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function quoted(value) {
|
|
97
|
+
const text = cleanText(value);
|
|
98
|
+
return `"${text.length > DETAIL_LENGTH ? `${text.substring(0, DETAIL_LENGTH)}...` : text}"`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function registrableDomain(host) {
|
|
102
|
+
host = domainToASCII(String(host ?? '').toLowerCase()) || String(host ?? '').toLowerCase();
|
|
103
|
+
return getDomain(host) || host || null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function addressDomain(address) {
|
|
107
|
+
const match = /@([^\s>@]+)\s*>?\s*$/.exec(String(address ?? ''));
|
|
108
|
+
return match ? registrableDomain(match[1]) : null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// "Name <address>" or a bare address, as the From and Reply-To values are formatted
|
|
112
|
+
function splitAddress(value) {
|
|
113
|
+
value = String(value ?? '').trim();
|
|
114
|
+
const match = /^(.*?)\s*<([^<>]+)>\s*$/.exec(value);
|
|
115
|
+
if (match) {
|
|
116
|
+
return { name: match[1].replace(/^"|"$/g, '').trim(), address: match[2].trim() };
|
|
117
|
+
}
|
|
118
|
+
return { name: '', address: value };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// A label is a lookalike when it mixes Latin letters with letters of another script: "paypal"
|
|
122
|
+
// spelled with a Cyrillic "a" reads as the brand and resolves elsewhere. A label written entirely in
|
|
123
|
+
// another script is a normal internationalised name
|
|
124
|
+
function isLookalikeHost(host) {
|
|
125
|
+
return domainToUnicode(String(host ?? ''))
|
|
126
|
+
.split('.')
|
|
127
|
+
.some(label => LATIN.test(label) && NON_LATIN_LETTER.test(label));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The host a browser would connect to: tabs and newlines are dropped, leading and trailing
|
|
131
|
+
// controls and spaces stripped, a scheme-relative or backslashed form resolved, the host
|
|
132
|
+
// lower-cased, percent-decoded and punycoded, all by the URL parser. Only http and https count
|
|
133
|
+
function linkHost(href) {
|
|
134
|
+
href = String(href ?? '')
|
|
135
|
+
.replace(/[\t\n\r]/g, '')
|
|
136
|
+
// eslint-disable-next-line no-control-regex
|
|
137
|
+
.replace(/^[\u0000- ]+|[\u0000- ]+$/g, '');
|
|
138
|
+
let url;
|
|
139
|
+
try {
|
|
140
|
+
url = new URL(href, 'https://base.invalid/');
|
|
141
|
+
} catch {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.hostname === 'base.invalid') {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
return url.hostname;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Anchor text that names a host or URL itself, which a reader takes as the destination.
|
|
151
|
+
// Trailing punctuation is not part of it. A host written as userinfo ("paypal.com@evil.example")
|
|
152
|
+
// is what the reader takes in first, so it counts when it is a real name; otherwise the userinfo
|
|
153
|
+
// is dropped the way a browser drops it
|
|
154
|
+
const HOST_START = /(?:^|[\s(<"'[])(?:https?:\/\/)?/.source;
|
|
155
|
+
const HOST = /((?:[\p{L}\p{N}-]+\.)+\p{L}{2,})/.source;
|
|
156
|
+
const HOST_AS_USERINFO = new RegExp(`${HOST_START}${HOST}@`, 'iu');
|
|
157
|
+
const HOST_IN_TEXT = new RegExp(`${HOST_START}(?:[^\\s/@]+@)?${HOST}(?=$|[\\s/?#:,.;!)\\]>"'])`, 'iu');
|
|
158
|
+
|
|
159
|
+
function hostInText(text) {
|
|
160
|
+
text = cleanText(text);
|
|
161
|
+
const userinfo = HOST_AS_USERINFO.exec(text);
|
|
162
|
+
if (userinfo && parseDomain(userinfo[1]).isIcann) {
|
|
163
|
+
return userinfo[1].toLowerCase();
|
|
164
|
+
}
|
|
165
|
+
const match = HOST_IN_TEXT.exec(text);
|
|
166
|
+
return match ? match[1].toLowerCase() : null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function urlsInText(text) {
|
|
170
|
+
return (String(text ?? '').match(/https?:\/\/[^\s<>"')\]]+/gi) || []).map(url => ({ href: url, text: '' }));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function normalizedFilename(filename) {
|
|
174
|
+
let name = cleanText(filename);
|
|
175
|
+
try {
|
|
176
|
+
name = decodeURIComponent(name);
|
|
177
|
+
} catch {
|
|
178
|
+
// not percent-encoded, which is the usual case
|
|
179
|
+
}
|
|
180
|
+
// Windows drops trailing dots and spaces when saving
|
|
181
|
+
return name.replace(/[.\s]+$/, '');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function extensionOf(name) {
|
|
185
|
+
const match = /\.([a-z0-9-]+)$/i.exec(name);
|
|
186
|
+
return match ? match[1].toLowerCase() : '';
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Runs the checks on a message
|
|
191
|
+
*
|
|
192
|
+
* @param {Object} message
|
|
193
|
+
* @param {string} [message.from] - Sender as "Name <address>"
|
|
194
|
+
* @param {string} [message.replyTo] - Reply-To as "Name <address>"
|
|
195
|
+
* @param {Array} [message.attachments] - Attachments with filename and contentType
|
|
196
|
+
* @param {Array} [message.links] - Every link of the HTML, with href and text, from visibleHtml()
|
|
197
|
+
* @param {string} [message.text] - Text body, read for links when there is no HTML
|
|
198
|
+
* @param {Object|null} [message.authentication] - As returned by authenticationBlock()
|
|
199
|
+
* @param {number} [message.hiddenElements] - Hidden elements removed from the HTML
|
|
200
|
+
* @param {number} [message.invisibleCharacters] - Invisible characters removed
|
|
201
|
+
* @returns {Array<{code: string, detail: string, floor: number}>}
|
|
202
|
+
*/
|
|
203
|
+
function collectSignals(message) {
|
|
204
|
+
const signals = [];
|
|
205
|
+
const seen = new Set();
|
|
206
|
+
const add = (code, detail) => {
|
|
207
|
+
const key = `${code}\n${detail}`;
|
|
208
|
+
if (!seen.has(key)) {
|
|
209
|
+
seen.add(key);
|
|
210
|
+
signals.push({ code, detail, floor: FLOORS[code] || 0 });
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
for (const attachment of [].concat(message.attachments || [])) {
|
|
215
|
+
const filename = normalizedFilename(attachment && attachment.filename);
|
|
216
|
+
const extension = extensionOf(filename);
|
|
217
|
+
const contentType = cleanText(attachment && attachment.contentType).toLowerCase();
|
|
218
|
+
if (EXECUTABLE_EXTENSIONS.has(extension) || EXECUTABLE_TYPES.has(contentType)) {
|
|
219
|
+
add('executableAttachment', quoted(filename || contentType));
|
|
220
|
+
} else if (SCRIPTABLE_EXTENSIONS.has(extension)) {
|
|
221
|
+
add('scriptableAttachment', quoted(filename));
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const from = splitAddress(message.from);
|
|
226
|
+
const fromDomain = addressDomain(from.address);
|
|
227
|
+
const replyTo = splitAddress(message.replyTo);
|
|
228
|
+
const replyToDomain = addressDomain(replyTo.address);
|
|
229
|
+
if (fromDomain && replyToDomain && fromDomain !== replyToDomain) {
|
|
230
|
+
add('replyToMismatch', `from ${quoted(fromDomain)}, replies go to ${quoted(replyToDomain)}`);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const nameDomain = addressDomain(from.name);
|
|
234
|
+
if (nameDomain && fromDomain && nameDomain !== fromDomain) {
|
|
235
|
+
add('displayNameAddressMismatch', `the display name reads as an address at ${quoted(nameDomain)}, the sender is at ${quoted(fromDomain)}`);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const links = Array.isArray(message.links) ? message.links : urlsInText(message.text);
|
|
239
|
+
const checked = new Set();
|
|
240
|
+
for (const link of links) {
|
|
241
|
+
const host = linkHost(link.href);
|
|
242
|
+
const shown = hostInText(link.text);
|
|
243
|
+
const key = `${host}\n${shown}`;
|
|
244
|
+
if (!host || checked.has(key)) {
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
checked.add(key);
|
|
248
|
+
if (isLookalikeHost(host)) {
|
|
249
|
+
add('lookalikeDomain', quoted(host));
|
|
250
|
+
}
|
|
251
|
+
if (shown && registrableDomain(shown) !== registrableDomain(host)) {
|
|
252
|
+
add('linkTargetMismatch', `link text says ${quoted(shown)}, the target is ${quoted(host)}`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (authenticationFailed(message.authentication)) {
|
|
257
|
+
const auth = message.authentication;
|
|
258
|
+
add('authenticationFailed', ['spf', 'dkim', 'dmarc'].map(method => `${method}=${auth[method] || 'none'}`).join(' '));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (message.hiddenElements > 0) {
|
|
262
|
+
add('hiddenContent', `${message.hiddenElements} hidden element(s) with text were left out`);
|
|
263
|
+
}
|
|
264
|
+
if (message.invisibleCharacters > 0) {
|
|
265
|
+
add('invisibleCharacters', `${message.invisibleCharacters} invisible character(s) were left out`);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return signals;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* The signals the model gets to see: the ones that carry a floor, without it
|
|
273
|
+
*
|
|
274
|
+
* @param {Array} signals - As returned by collectSignals()
|
|
275
|
+
* @returns {Array<{code: string, detail: string}>}
|
|
276
|
+
*/
|
|
277
|
+
function modelSignals(signals) {
|
|
278
|
+
return signals.filter(signal => signal.floor > 0).map(({ code, detail }) => ({ code, detail }));
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Applies the signals to the model's answer: the risk score cannot be below their floor, and
|
|
283
|
+
* the codes of the ones that carry one are listed with the assessment so a consumer sees what
|
|
284
|
+
* was found
|
|
285
|
+
*
|
|
286
|
+
* @param {Object} result - Normalized model output, changed in place
|
|
287
|
+
* @param {Array} signals - As returned by collectSignals()
|
|
288
|
+
* @returns {Object} The same result
|
|
289
|
+
*/
|
|
290
|
+
function applySignals(result, signals) {
|
|
291
|
+
const scored = signals.filter(signal => signal.floor > 0);
|
|
292
|
+
if (!scored.length) {
|
|
293
|
+
return result;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const riskAssessment = result.riskAssessment && typeof result.riskAssessment === 'object' ? result.riskAssessment : {};
|
|
297
|
+
const risk = Number.isFinite(riskAssessment.risk) ? riskAssessment.risk : 0;
|
|
298
|
+
const floor = Math.max(...scored.map(signal => signal.floor));
|
|
299
|
+
|
|
300
|
+
if (floor > risk) {
|
|
301
|
+
const raised = scored.filter(signal => signal.floor > risk).map(signal => `${signal.code}: ${signal.detail}`);
|
|
302
|
+
riskAssessment.risk = floor;
|
|
303
|
+
riskAssessment.assessment = [riskAssessment.assessment, `Checks run on the message found: ${raised.join('; ')}.`].filter(Boolean).join(' ');
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
riskAssessment.signals = scored.map(signal => signal.code);
|
|
307
|
+
result.riskAssessment = riskAssessment;
|
|
308
|
+
return result;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
module.exports = { collectSignals, modelSignals, applySignals, isLookalikeHost, splitAddress };
|
package/lib/token-estimate.js
CHANGED
|
@@ -128,4 +128,4 @@ function fitPrompt({ text, maxLength, maxTokens, overhead }) {
|
|
|
128
128
|
return { text: fitted, charactersRemoved: text.length - fitted.length };
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
-
module.exports = { estimateTokens, fitLength, fitPrompt };
|
|
131
|
+
module.exports = { estimateTokens, fitLength, fitPrompt, DEFAULT_MAX_ALLOWED_TOKENS };
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { parseDocument } = require('htmlparser2');
|
|
4
|
+
const { default: serialize } = require('dom-serializer');
|
|
5
|
+
const { isTag, isText, isComment, hasChildren, textContent, findAll, findOne, prependChild, removeElement } = require('domutils');
|
|
6
|
+
|
|
7
|
+
// What the reader never sees must not reach the model either: an email can carry instructions
|
|
8
|
+
// for an AI in text a mail client does not render, and the summary has to describe the message
|
|
9
|
+
// as it looks to the person it was sent to. The links are collected before anything is removed,
|
|
10
|
+
// because the checks run on them must see every link the message carries, hidden or not
|
|
11
|
+
|
|
12
|
+
// Elements whose content is never rendered as text
|
|
13
|
+
const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'title', 'iframe', 'object', 'embed']);
|
|
14
|
+
|
|
15
|
+
// Comments and quoted strings inside a style attribute, which carry no declarations
|
|
16
|
+
const STYLE_NOISE = /\/\*[\s\S]*?\*\/|"[^"]*"|'[^']*'/g;
|
|
17
|
+
|
|
18
|
+
// Outlook for Windows shows what a conditional comment wraps; the markers go, the content stays
|
|
19
|
+
const CONDITIONAL_COMMENT = /<!--\[if [^\]]*\]>|<!\[endif\]-->/gi;
|
|
20
|
+
|
|
21
|
+
// Characters that take no space on screen: zero-width joiners and spaces, soft hyphens, the
|
|
22
|
+
// bidirectional controls and the word joiner. Removing them changes nothing the reader sees and
|
|
23
|
+
// stops them splitting words the model should recognise or reordering text it should read
|
|
24
|
+
const INVISIBLE_CHARS = /[\u00ad\u200b-\u200f\u2028-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/g;
|
|
25
|
+
|
|
26
|
+
// Only what reliably hides text. Zero sizes of boxes and negative positions depend on other
|
|
27
|
+
// properties to hide anything, so they are left alone rather than dropping text the reader sees
|
|
28
|
+
function isHiddenStyle(style) {
|
|
29
|
+
style = String(style ?? '').replace(STYLE_NOISE, ' ');
|
|
30
|
+
if (!style.trim()) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
for (const declaration of style.split(';')) {
|
|
34
|
+
const match = /^\s*([a-z-]+)\s*:\s*([^!]*)/i.exec(declaration);
|
|
35
|
+
if (!match) {
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
const property = match[1].toLowerCase();
|
|
39
|
+
const value = match[2].trim().toLowerCase();
|
|
40
|
+
const number = parseFloat(value);
|
|
41
|
+
switch (property) {
|
|
42
|
+
case 'display':
|
|
43
|
+
if (value === 'none') {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
break;
|
|
47
|
+
case 'visibility':
|
|
48
|
+
if (value === 'hidden' || value === 'collapse') {
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
break;
|
|
52
|
+
case 'opacity':
|
|
53
|
+
if (Number.isFinite(number) && number < 0.1) {
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
break;
|
|
57
|
+
case 'font-size':
|
|
58
|
+
// zero in any unit, or below one pixel
|
|
59
|
+
if (Number.isFinite(number) && (number === 0 || (number < 1 && /^[\d.]+(?:px|pt)?$/.test(value)))) {
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
break;
|
|
63
|
+
case 'text-indent':
|
|
64
|
+
if (Number.isFinite(number) && number <= -1000) {
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isHiddenElement(node) {
|
|
74
|
+
const attribs = node.attribs || {};
|
|
75
|
+
const style = attribs.style || '';
|
|
76
|
+
// the hidden attribute is a user agent rule, which an author display value overrides
|
|
77
|
+
if ('hidden' in attribs && !/display\s*:\s*(?!none)/i.test(style.replace(STYLE_NOISE, ' '))) {
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
return isHiddenStyle(style);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function hasText(node) {
|
|
84
|
+
if (isText(node)) {
|
|
85
|
+
return /\S/.test(node.data || '');
|
|
86
|
+
}
|
|
87
|
+
return hasChildren(node) && node.children.some(hasText);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function stripHidden(node, stats) {
|
|
91
|
+
if (!hasChildren(node)) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
node.children = node.children.filter(child => {
|
|
95
|
+
if (isComment(child)) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
if (isText(child)) {
|
|
99
|
+
// before the conversion, which would turn a zero-width space into a plain one
|
|
100
|
+
const cleaned = child.data.replace(INVISIBLE_CHARS, '');
|
|
101
|
+
stats.invisibleCharacters += child.data.length - cleaned.length;
|
|
102
|
+
child.data = cleaned;
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
if (!isTag(child)) {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
if (HIDDEN_TAGS.has(child.name)) {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
if (isHiddenElement(child)) {
|
|
112
|
+
// a layout element with no text in it is not hidden content, only a spacer
|
|
113
|
+
if (hasText(child)) {
|
|
114
|
+
stats.hiddenElements++;
|
|
115
|
+
}
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
return true;
|
|
119
|
+
});
|
|
120
|
+
for (const child of node.children) {
|
|
121
|
+
stripHidden(child, stats);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// What the reader takes as the link: its text, and the alt and title of an image standing in
|
|
126
|
+
// for it
|
|
127
|
+
function linkText(node) {
|
|
128
|
+
const parts = [textContent(node), node.attribs.title || ''];
|
|
129
|
+
for (const image of findAll(child => child.name === 'img', node.children)) {
|
|
130
|
+
parts.push(image.attribs.alt || '', image.attribs.title || '');
|
|
131
|
+
}
|
|
132
|
+
return parts.join(' ').replace(/\s+/g, ' ').trim();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function collectLinks(document) {
|
|
136
|
+
const targets = findAll(
|
|
137
|
+
node => ((node.name === 'a' || node.name === 'area') && !!node.attribs.href) || (node.name === 'form' && !!node.attribs.action),
|
|
138
|
+
document.children
|
|
139
|
+
);
|
|
140
|
+
return targets.map(node => ({ href: node.attribs.href || node.attribs.action, text: linkText(node) }));
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Parses an HTML message once: every link it carries, for the checks, and the document as the
|
|
145
|
+
* reader sees it, for the model
|
|
146
|
+
*
|
|
147
|
+
* @param {string} html
|
|
148
|
+
* @returns {{links: Array<{href: string, text: string}>, hiddenElements: number, invisibleCharacters: number, html: Function}} The links, how many styled-away elements carrying text were dropped, how many invisible characters, and the visible HTML as a function, serialised only when asked for
|
|
149
|
+
*/
|
|
150
|
+
// A browser shows flow content a message put inside <head>, the converter reads only <body>:
|
|
151
|
+
// what is left of the head after the metadata went moves to the front of the body
|
|
152
|
+
function surfaceHead(document) {
|
|
153
|
+
const head = findOne(node => node.name === 'head', document.children);
|
|
154
|
+
if (!head) {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const body = findOne(node => node.name === 'body', document.children);
|
|
158
|
+
if (!body) {
|
|
159
|
+
head.name = 'div';
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
for (const child of head.children.slice().reverse()) {
|
|
163
|
+
prependChild(body, child);
|
|
164
|
+
}
|
|
165
|
+
removeElement(head);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function visibleHtml(html) {
|
|
169
|
+
const document = parseDocument(String(html ?? '').replace(CONDITIONAL_COMMENT, ''));
|
|
170
|
+
const links = collectLinks(document);
|
|
171
|
+
const stats = { hiddenElements: 0, invisibleCharacters: 0 };
|
|
172
|
+
stripHidden(document, stats);
|
|
173
|
+
surfaceHead(document);
|
|
174
|
+
return { links, hiddenElements: stats.hiddenElements, invisibleCharacters: stats.invisibleCharacters, html: () => serialize(document) };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Removes the characters that take no space on screen
|
|
179
|
+
*
|
|
180
|
+
* @param {string} text
|
|
181
|
+
* @returns {{text: string, invisibleCharacters: number}}
|
|
182
|
+
*/
|
|
183
|
+
function visibleText(text) {
|
|
184
|
+
text = String(text ?? '');
|
|
185
|
+
const matches = text.match(INVISIBLE_CHARS);
|
|
186
|
+
return { text: matches ? text.replace(INVISIBLE_CHARS, '') : text, invisibleCharacters: matches ? matches.length : 0 };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
module.exports = { visibleHtml, visibleText, INVISIBLE_CHARS };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@postalsys/email-ai-tools",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "Summarize and risk-score email messages with an OpenAI-compatible chat model",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -31,7 +31,11 @@
|
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"@postalsys/email-text-tools": "2.4.18",
|
|
34
|
+
"dom-serializer": "2.0.0",
|
|
35
|
+
"domutils": "3.2.2",
|
|
36
|
+
"htmlparser2": "10.1.0",
|
|
34
37
|
"libmime": "5.4.6",
|
|
38
|
+
"tldts": "7.4.16",
|
|
35
39
|
"undici": "7.30.0"
|
|
36
40
|
},
|
|
37
41
|
"engines": {
|