@postalsys/email-ai-tools 1.14.14 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,346 +0,0 @@
1
- 'use strict';
2
-
3
- const libmime = require('libmime');
4
- const addressparser = require('nodemailer/lib/addressparser');
5
- const { htmlToText } = require('@postalsys/email-text-tools');
6
- const punycode = require('punycode.js');
7
- const { apiRequest } = require('./api-request');
8
- const { estimateTokens, splitByTokens, keepSurrogatePair, CHUNK_ESTIMATE, MAX_ALLOWED_TEXT_LENGTH } = require('./token-estimate');
9
- const linkifyIt = require('linkify-it');
10
- const tlds = require('tlds');
11
-
12
- const linkify = linkifyIt()
13
- .tlds(tlds) // Reload with full tlds list
14
- .tlds('onion', true) // Add unofficial `.onion` domain
15
- .add('git:', 'http:') // Add `git:` protocol as "alias"
16
- .set({ fuzzyIP: true });
17
-
18
- const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
19
-
20
- const OPENAI_API_URL = '/v1/embeddings';
21
-
22
- // Chunks sent in one embeddings request. OpenAI accepts far more, but some compatible services
23
- // (older Azure OpenAI deployments) cap the input array at 16.
24
- const DEFAULT_CHUNKS_PER_REQUEST = 16;
25
- const MAX_CHUNKS_PER_REQUEST = 64;
26
-
27
- // Sends one embeddings request for a string or an array of strings. Resolves with the
28
- // embeddings in input order and the request time. The response must carry exactly one entry per
29
- // input, so a reply without a `data` array is rejected with InvalidResponse even for a single
30
- // string input (it used to resolve with an undefined embedding).
31
- async function requestEmbeddings(input, apiToken, opts) {
32
- opts = opts || {};
33
-
34
- const payload = {
35
- model: opts.gptModel || 'text-embedding-ada-002',
36
- input
37
- };
38
-
39
- if (opts.user) {
40
- payload.user = opts.user;
41
- }
42
-
43
- const { data, time } = await apiRequest(getApiUrl(opts.baseApiUrl || OPENAI_API_BASE_URL, OPENAI_API_URL), {
44
- apiToken,
45
- payload,
46
- dispatcher: opts.dispatcher,
47
- signal: opts.signal,
48
- verbose: opts.verbose
49
- });
50
-
51
- const inputCount = [].concat(input).length;
52
- const entries = Array.isArray(data.data) ? data.data.slice() : [];
53
- if (entries.length !== inputCount) {
54
- const error = new Error(`Embeddings response has ${entries.length} entries for ${inputCount} inputs`);
55
- error.code = 'InvalidResponse';
56
- throw error;
57
- }
58
- // entries carry their input position, do not rely on the array order
59
- entries.sort((a, b) => ((a && a.index) || 0) - ((b && b.index) || 0));
60
-
61
- return { vectors: entries.map(entry => entry && entry.embedding), time };
62
- }
63
-
64
- /**
65
- * Returns the embedding vector for a single chunk of text
66
- *
67
- * @throws {Error} InvalidResponse if the API reply does not carry exactly one embedding
68
- */
69
- async function getChunkEmbeddings(chunk, apiToken, opts) {
70
- const {
71
- vectors: [embedding],
72
- time
73
- } = await requestEmbeddings(chunk, apiToken, opts);
74
-
75
- return {
76
- chunk,
77
- embedding,
78
- _time: time
79
- };
80
- }
81
-
82
- class Embedder {
83
- constructor(message, apiToken, opts) {
84
- this.message = message;
85
- this.apiToken = apiToken;
86
-
87
- opts = opts || {};
88
- this.chunkSize = opts.chunkSize || 400;
89
- this.gptModel = opts.gptModel || 'text-embedding-ada-002';
90
- this.maxTextLength = opts.maxTextLength || MAX_ALLOWED_TEXT_LENGTH;
91
- this.chunksPerRequest = Math.min(Math.max(Number(opts.chunksPerRequest) || DEFAULT_CHUNKS_PER_REQUEST, 1), MAX_CHUNKS_PER_REQUEST);
92
- this.signal = opts.signal;
93
-
94
- // Forwarded to every per-chunk embeddings request
95
- this.requestOpts = {
96
- gptModel: this.gptModel,
97
- baseApiUrl: opts.baseApiUrl,
98
- user: opts.user,
99
- dispatcher: opts.dispatcher,
100
- signal: opts.signal,
101
- verbose: opts.verbose
102
- };
103
-
104
- this.addressHeaders = new Map();
105
-
106
- let subject;
107
-
108
- for (const { key: headerKey, value } of message.headers || []) {
109
- switch (headerKey) {
110
- case 'from':
111
- case 'to':
112
- case 'cc':
113
- case 'bcc':
114
- {
115
- // join to, cc, and bcc entries
116
- let key = headerKey === 'from' ? headerKey : 'to';
117
-
118
- let addressList;
119
-
120
- if (this.addressHeaders.has(key)) {
121
- addressList = this.addressHeaders.get(key);
122
- } else {
123
- addressList = [];
124
- this.addressHeaders.set(key, addressList);
125
- }
126
-
127
- addressList.push(...this.formatAddresses(addressparser(value, { flatten: true })));
128
- }
129
- break;
130
-
131
- case 'subject': {
132
- subject = (value || '').toString().trim();
133
- try {
134
- subject = libmime.decodeWords(subject);
135
- } catch {
136
- // ignore?
137
- }
138
- if (subject) {
139
- this.subject = subject;
140
- }
141
- break;
142
- }
143
-
144
- case 'date': {
145
- let date;
146
- try {
147
- date = new Date((value || '').toString().trim());
148
- if (date && date.toString() !== 'Invalid Date') {
149
- this.date = date.toUTCString();
150
- }
151
- } catch {
152
- // ignore?
153
- }
154
- break;
155
- }
156
- }
157
- }
158
-
159
- for (let key of ['from', 'to']) {
160
- if (this.addressHeaders.has(key)) {
161
- const addressList = this.addressHeaders.get(key);
162
- if (!addressList || !addressList.length) {
163
- this.addressHeaders.delete(key);
164
- continue;
165
- }
166
- this.addressHeaders.set(key, this.getAddressString(addressList));
167
- }
168
- }
169
-
170
- let text = (message.text || '').toString().trim();
171
- if (message.html && (!text || message.html.length >= text.length)) {
172
- text = (htmlToText(message.html) || '').trim();
173
- }
174
-
175
- if (text.length > this.maxTextLength) {
176
- text = text.substring(0, keepSurrogatePair(text, this.maxTextLength));
177
- }
178
-
179
- // replace links
180
-
181
- this.text = this.prepareLinks(text);
182
- }
183
-
184
- prepareLinks(text) {
185
- try {
186
- let links = linkify.match(text);
187
- if (links && links.length) {
188
- let parts = [];
189
- let cursor = 0;
190
- for (let link of links) {
191
- if (cursor < link.index) {
192
- parts.push({
193
- type: 'text',
194
- content: text.substring(cursor, link.index)
195
- });
196
- cursor = link.index;
197
- }
198
- parts.push(Object.assign({ type: 'link' }, link));
199
- cursor = link.lastIndex;
200
- }
201
-
202
- if (cursor < text.length) {
203
- parts.push({
204
- type: 'text',
205
- content: text.substr(cursor)
206
- });
207
- }
208
-
209
- return parts
210
- .map(part => {
211
- switch (part.type) {
212
- case 'text': {
213
- // normal text, escape HTML
214
- return part.content;
215
- }
216
- case 'link':
217
- // URL with html escaped text content and URL
218
- try {
219
- const parsedUrl = new URL(part.url);
220
- return `${parsedUrl.protocol}//${parsedUrl.host}`;
221
- } catch {
222
- return ' ';
223
- }
224
- }
225
- return '';
226
- })
227
- .join('');
228
- }
229
- } catch {
230
- // ignore?
231
- }
232
-
233
- // No links or exception, so HTML escape everything
234
- return text;
235
- }
236
-
237
- formatAddresses(addresses) {
238
- let result = [];
239
- for (let address of [].concat(addresses || [])) {
240
- if (address.group) {
241
- result = result.concat(this.formatAddresses(address.group));
242
- } else {
243
- let name = address.name || '';
244
- let addr = address.address || '';
245
- try {
246
- name = libmime.decodeWords(name);
247
- } catch {
248
- // ignore?
249
- }
250
-
251
- if (/@xn--/.test(addr)) {
252
- addr = addr.substr(0, addr.lastIndexOf('@') + 1) + punycode.toUnicode(addr.substr(addr.lastIndexOf('@') + 1));
253
- }
254
-
255
- result.push({ name, address: addr });
256
- }
257
- }
258
- return result;
259
- }
260
-
261
- getAddressString(addresses) {
262
- return []
263
- .concat(addresses)
264
- .map(address => {
265
- let res = [];
266
- if (address.name) {
267
- res.push(address.name);
268
- }
269
- if (address.address) {
270
- res.push(`<${address.address}>`);
271
- }
272
- return res.join(' ');
273
- })
274
- .filter(val => val)
275
- .join(' ; ');
276
- }
277
-
278
- getChunks() {
279
- let headerLines = [];
280
- for (let [key, value] of this.addressHeaders.entries()) {
281
- headerLines.push(`${key}: ${value.replace(/\s/g, ' ')}`);
282
- }
283
- if (this.subject) {
284
- headerLines.push(`subject: ${this.subject}`);
285
- }
286
- if (this.date) {
287
- headerLines.push(`date: ${this.date}`);
288
- }
289
- if (this.message.attachments?.length) {
290
- let attachments = this.message.attachments.map(attachment => attachment.filename?.replace(/\s/g, ' ').trim()).filter(val => val);
291
- if (attachments.length) {
292
- headerLines.push(`attachments: ${attachments.join(' ; ')}`);
293
- }
294
- }
295
-
296
- let prompt = `${headerLines.join('\n')}\n\n`;
297
-
298
- let prefixTokens = estimateTokens(prompt, CHUNK_ESTIMATE);
299
- // If prefix is very large, then use larger chunks, so that each chunk contains at least 200 tokens of text
300
- let allowedTokens = Math.max(prefixTokens + 200, this.chunkSize);
301
-
302
- let textTokensChunkSize = allowedTokens - prefixTokens;
303
-
304
- let textChunks = [];
305
- if (this.text) {
306
- let preparedText = this.text
307
- .replace(/\r?\n/g, '\n')
308
- .replace(/^\s*>.*$/gm, '')
309
- .replace(/^\s+$/gm, '')
310
- .replace(/\n\n+/g, '\n\n');
311
-
312
- textChunks = splitByTokens(preparedText, textTokensChunkSize);
313
- } else {
314
- textChunks.push('');
315
- }
316
-
317
- return textChunks.map(value => `${prompt}${value}`);
318
- }
319
-
320
- async getEmbeddings() {
321
- let chunks = this.getChunks();
322
-
323
- let embeddings = [];
324
-
325
- for (let i = 0; i < chunks.length; i += this.chunksPerRequest) {
326
- this.signal?.throwIfAborted();
327
-
328
- const batch = chunks.slice(i, i + this.chunksPerRequest);
329
-
330
- // a single chunk goes out as a plain string, as it always did
331
- const { vectors, time } = await requestEmbeddings(batch.length === 1 ? batch[0] : batch, this.apiToken, this.requestOpts);
332
-
333
- batch.forEach((chunk, j) => {
334
- embeddings.push({ chunk, embedding: vectors[j], _time: time });
335
- });
336
- }
337
-
338
- return { model: this.gptModel, embeddings };
339
- }
340
- }
341
-
342
- module.exports.getChunkEmbeddings = getChunkEmbeddings;
343
- module.exports.generateEmbeddings = async (message, apiToken, opts) => {
344
- let embedder = new Embedder(message, apiToken, opts);
345
- return await embedder.getEmbeddings();
346
- };
@@ -1,195 +0,0 @@
1
- 'use strict';
2
-
3
- const { htmlToText } = require('@postalsys/email-text-tools');
4
- const { apiRequest } = require('./api-request');
5
- const { fitPrompt, DEFAULT_MAX_ALLOWED_TOKENS } = require('./token-estimate');
6
-
7
- const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
8
-
9
- const OPENAI_API_URL = '/v1/chat/completions';
10
-
11
- const DEFAULT_ALLOWED_HEADERS = [
12
- 'from',
13
- 'to',
14
- 'cc',
15
- 'bcc',
16
- 'subject',
17
- 'mime-version',
18
- 'authentication-results',
19
- 'arc-authentication-results',
20
- 'arc-message-signature',
21
- 'arc-seal',
22
- 'date',
23
- 'content-type',
24
- 'list-id'
25
- ];
26
-
27
- const DEFAULT_SYSTEM_PROMPT = `
28
- I want you to act as are an IT security expert that monitors emails for suspicious and risky activity.
29
- `
30
- .replace(/\s+/g, ' ')
31
- .trim();
32
-
33
- const DEFAULT_USER_PROMPT = `
34
- Instructions:
35
- - You are an IT security expert scanning incoming emails to detect and block fraud attempts.
36
- - Your task is to monitor and analyze incoming emails, which consist of the message headers, a list of attachments, and text content
37
- - Your analysis should contain (but is not limited to) the following risk factors:
38
- - Does the email include links with domain names that contain typos or homoglyphs that might mislead the user about the actual target of the link
39
- - Does the sender address of the email not seem to match the persona or organization the sender email claims to be
40
- - Does the email promise the user an extremely good financial outcome
41
- - Does the email promise unclaimed money or goods
42
- - Does the email offer a vague business opportunity with no specific details
43
- - Does the email suggest there is a severe penalty if the user does not act as requested
44
- - Does the email claim that there are technical issues with the user's email account
45
- - Does the email offer services or activities that are not suitable for underage persons
46
- - Does the sender's email look like a throwaway address
47
- - Does the sender's email look like it might be spoofed
48
- - Does the email contain attachments where the name of the attachment might be misleading and suggest a different file format than is actually used
49
- - Does the email contain attachments that might be executable files
50
- - Provide a risk score for the email using the following scale: 1 - 5 (where 1 is low risk, and 5 is high risk), taking into account what may happen if a user acts by the instructions given in the email.
51
- - Provide a short single-sentence assessment text that includes details about issues that increase the risk score, do not disclose details that decrease the risk score or do not affect it.
52
- - Respond with a JSON formatted structure with a numeric risk score as "risk" property and the assessment as the "assessment" property. Do not write any other explanations.
53
-
54
- Facts:
55
-
56
- - An email might contain an "authentication-results" result header that indicates if the message passed SPF, DKIM, ARC, and DMARC checks
57
- - Having a valid SPF, DKIM, and DMARC increases the chances that the sender domain name is not spoofed
58
- - For valid SPF, the "authentication-results" header must include "spf=pass"
59
- - For valid DKIM, the "authentication-results" header must include "dkim=pass"
60
- - For valid DMARC, the "authentication-results" header must include "dmarc=pass"
61
- - For valid ARC, the "authentication-results" header must include "arc=pass"
62
- - Throwaway email addresses might contain a word or a name and more than one number in the username of the email address
63
- - Throwaway email addresses might use a randomly generated or hex text string as the username of the email address
64
- - Throwaway email addresses might use free email services like gmail.com, outlook.com, hotmail.com, yahoo.com, aol.com, etc
65
-
66
- - An email consists of message headers, an attachments list, and text content
67
- - The email to analyze is formatted in a JSON format
68
- - The email structure includes a property "headers" that contains an array of header values.
69
- - Each header contains two properties, "key" as the header field key name and "value" as the header value without the key prefix
70
- - The email structure includes a property "attachments" that contains an array of attachments.
71
- - Each attachment includes a "filename" property that describes the file name, "contentType" property that describes the Content-Type value of the attachment
72
- - The email includes a "text" property for the text content
73
-
74
- Analyze the following email:
75
- `.trim();
76
-
77
- async function riskAnalysis(message, apiToken, opts) {
78
- opts = opts || {};
79
-
80
- let baseApiUrl = opts.baseApiUrl || OPENAI_API_BASE_URL;
81
-
82
- let systemPrompt = opts.systemPrompt || DEFAULT_SYSTEM_PROMPT;
83
- let userPrompt = opts.userPrompt || DEFAULT_USER_PROMPT;
84
-
85
- let maxAllowedTokens = opts.maxTokens || DEFAULT_MAX_ALLOWED_TOKENS;
86
- let gptModel = opts.gptModel || 'gpt-5-mini';
87
-
88
- let text = message.text || '';
89
- if (message.html && (!text || message.html.length > text.length * 2)) {
90
- text = htmlToText(message.html);
91
- }
92
-
93
- const headerSeen = new Set();
94
- const content = {
95
- headers: []
96
- .concat(message.headers || [])
97
- .filter(
98
- // use a whitelist
99
- header => DEFAULT_ALLOWED_HEADERS.includes(header.key)
100
- )
101
- .filter(header => {
102
- // only keep the latest
103
- if (['authentication-results'].includes(header.key)) {
104
- if (headerSeen.has(header.key)) {
105
- return false;
106
- }
107
- headerSeen.add(header.key);
108
- }
109
- return true;
110
- }),
111
- attachments: [].concat(message.attachments || []).map(attachment => ({ filename: attachment.filename, contentType: attachment.contentType }))
112
- };
113
-
114
- const {
115
- prompt,
116
- text: promptText,
117
- charactersRemoved
118
- } = fitPrompt({
119
- text,
120
- maxTokens: maxAllowedTokens,
121
- build: bodyText => `${userPrompt}
122
-
123
- ${JSON.stringify(Object.assign({}, content, { text: bodyText }))}`
124
- });
125
-
126
- let payload = {
127
- model: gptModel,
128
- messages: [
129
- {
130
- role: 'system',
131
- content: `${systemPrompt}`
132
- },
133
- {
134
- role: 'user',
135
- content: prompt
136
- }
137
- ]
138
- };
139
-
140
- if (opts.user) {
141
- payload.user = opts.user;
142
- }
143
-
144
- if (opts.temperature && !isNaN(opts.temperature)) {
145
- payload.temperature = Number(opts.temperature);
146
- }
147
-
148
- if (opts.topP && !isNaN(opts.topP)) {
149
- payload.top_p = Number(opts.topP);
150
- }
151
-
152
- const { data, time } = await apiRequest(getApiUrl(baseApiUrl, OPENAI_API_URL), {
153
- apiToken,
154
- payload,
155
- dispatcher: opts.dispatcher,
156
- signal: opts.signal,
157
- verbose: opts.verbose
158
- });
159
-
160
- let values;
161
- const output =
162
- data &&
163
- data.choices &&
164
- data.choices
165
- .filter(msg => msg && msg.message && msg.message.role === 'assistant' && msg.message.content)
166
- .sort((a, b) => ((a && a.index) || 0) - ((b && b.index) || 0))
167
- .map(msg => msg.message.content)
168
- .join('\n')
169
- .trim()
170
- .replace(/^\s*"|"\s*$/g, '')
171
- .trim();
172
-
173
- try {
174
- values = JSON.parse(output);
175
- values.risk = Number(values.risk) || -1;
176
- } catch {
177
- let error = new Error('Failed to parse output from OpenAI API');
178
- error.textContent = output;
179
- throw error;
180
- }
181
-
182
- const response = Object.assign({ id: null, tokens: null, model: null }, values, {
183
- id: data && data.id,
184
- tokens: data && data.usage && data.usage.total_tokens,
185
- model: gptModel,
186
-
187
- _text: promptText,
188
- _time: time,
189
- _cr: charactersRemoved
190
- });
191
-
192
- return response;
193
- }
194
-
195
- module.exports = riskAnalysis;