@postalsys/email-ai-tools 2.2.2 → 2.2.3

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,3 +1,3 @@
1
1
  {
2
- ".": "2.2.2"
2
+ ".": "2.2.3"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.2.3](https://github.com/postalsys/email-ai-tools/compare/v2.2.2...v2.2.3) (2026-10-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * bound the work a message can make the summariser do, and never pass model-written signals through as code-derived ([d4a1512](https://github.com/postalsys/email-ai-tools/commit/d4a1512d7882746f2f8fc3e0448a6583f54b9677))
9
+
3
10
  ## [2.2.2](https://github.com/postalsys/email-ai-tools/compare/v2.2.1...v2.2.2) (2026-10-14)
4
11
 
5
12
 
package/README.md CHANGED
@@ -34,7 +34,7 @@ console.log(result);
34
34
  // summary: 'Jane asks to review the Q4 roadmap tomorrow at 2pm in room A.',
35
35
  // sentiment: 'positive',
36
36
  // shouldReply: true,
37
- // riskAssessment: { risk: 1 },
37
+ // riskAssessment: { risk: 1, signals: [] },
38
38
  // events: [{ description: 'Q4 roadmap review', type: 'meeting', startTime: '2022-10-18T14:00:00', location: 'room A' }],
39
39
  // actions: [{ description: 'Confirm the meeting' }]
40
40
  // }
@@ -86,7 +86,7 @@ The email is untrusted input, and the library does not leave its verdict to the
86
86
 
87
87
  - **Hidden text is removed.** Elements a mail client does not render (`display:none`, `visibility:hidden`, a font size below a pixel, an opacity below a tenth, a far negative text indent, the `hidden` attribute, scripts, styles, comments) are dropped before the HTML is converted, and zero-width, soft-hyphen and bidirectional control characters are removed from the text. The model reads what the recipient sees. Only rules that reliably hide text are applied, so content a client does show (`noscript`, SVG text, Outlook's conditional comments, boxes of zero size) stays.
88
88
  - **Signals are collected in code**, on the full message and before anything is removed, and the ones that carry a floor are passed to the model as `signals`: an executable or double-extension attachment (by extension or content type, after the name is normalised), an attachment a browser runs code from (HTML, SVG), a link whose text names a different host than its target (links read the way a browser does, hidden links included, image alt text counted as link text), a lookalike domain mixing scripts (a Cyrillic letter inside `paypal.com`, in unicode, punycode or percent encoding), a display name that reads as an address on another domain, a reply address on another domain, and a verified authentication failure. Each carries a quoted, cleaned detail.
89
- - **The risk score has a floor.** After the model answers, `riskAssessment.risk` is raised to the floor of the signals found (4 for an executable attachment or a lookalike domain, 3 for a link mismatch, a scriptable attachment, a display name address or a failed authentication, 2 for a reply address elsewhere), the assessment says what was found, and `riskAssessment.signals` lists the codes. A model talked into "risk 1" by text inside the message still delivers a 4 when the attachment is an executable. When the model's answer cannot be parsed, the error carries the signals.
89
+ - **The risk score has a floor.** After the model answers, `riskAssessment.risk` is raised to the floor of the signals found (4 for an executable attachment or a lookalike domain, 3 for a link mismatch, a scriptable attachment, a display name address or a failed authentication, 2 for a reply address elsewhere), the assessment says what was found, and `riskAssessment.signals` lists the codes. That list is always what the code found, an empty one when nothing was, whatever the model wrote there. A model talked into "risk 1" by text inside the message still delivers a 4 when the attachment is an executable. When the model's answer cannot be parsed, or the prompt cannot be fitted into the token budget, the error carries the signals.
90
90
  - **Authentication results are parsed, and trusted only when the server that wrote them is.** The topmost `Authentication-Results` header becomes an `authentication` block with the SPF, DKIM, DMARC and ARC results and a `verified` flag, and is kept out of `headers` so the model never reads it as text a sender could have written; the ARC results header is not passed on at all. The parser handles nested comments and quoted strings, and lets a failure win when a method is repeated. `verified` is true when the header's authserv-id is one of `options.trustedAuthservIds` or a host under one, or when the header carries no authserv-id and `options.acceptUnnamedAuthentication` is set (Microsoft 365 writes such headers). The default instructions tell the model that an unverified or missing verdict means unknown, not failed. The library sees headers by name, not by position, so it cannot tell whether the topmost header was written by the receiving server or arrived with the message: the caller decides what to trust accordingly, and should not trust a name a sender could guess.
91
91
 
92
92
  `generateSummary()` returns every signal it found, including the ones without a floor (hidden content and invisible characters removed), as a third property, `signals`, each with its `code`, `detail` and `floor`.
@@ -97,7 +97,7 @@ The system message carries the role, the rule that the email is untrusted data,
97
97
 
98
98
  ### Result
99
99
 
100
- `result` is the JSON object the model returned, with `null` and empty values removed. The properties the default instructions ask for are normalized: `sentiment` is lower-cased and must be one of `positive`, `neutral` or `negative`, `shouldReply` is a boolean, `riskAssessment.risk` is an integer from 1 to 5, and `events` and `actions` are arrays of objects. A value that cannot be made to fit is dropped. Properties that custom instructions ask for are passed on as they came.
100
+ `result` is the JSON object the model returned, with `null` and empty values removed. The properties the default instructions ask for are normalized: `sentiment` is lower-cased and must be one of `positive`, `neutral` or `negative`, `shouldReply` is a boolean, `riskAssessment.risk` is an integer from 1 to 5, `summary` and `riskAssessment.assessment` are cut at 1000 characters, and `events` and `actions` are arrays of at most 50 objects whose values are strings (cut the same way), numbers or booleans. A value that cannot be made to fit is dropped. Properties that custom instructions ask for are passed on as they came.
101
101
 
102
102
  `usage` holds the request id, the model name requested and the one the API reports it served, the token counts, the request time in milliseconds and how many characters were cut from the text to fit the budget.
103
103
 
@@ -8,6 +8,11 @@ const packageData = require('../package.json');
8
8
 
9
9
  const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
10
10
 
11
+ // How long one call may take in all, retries included, when the caller sets no deadline of its
12
+ // own. undici bounds each phase of a request but nothing bounds the sum, and a chat completion
13
+ // waits for its headers until the answer is complete
14
+ const DEFAULT_TIMEOUT = 5 * 60 * 1000;
15
+
11
16
  const MAX_RETRIES = 5;
12
17
  const RETRY_DELAY_MS = 1000;
13
18
  // A 429 asking for a longer pause than this fails right away instead of holding the caller
@@ -102,12 +107,14 @@ function errorMessage(apiError) {
102
107
  * @param {string} opts.apiToken - Sent as a Bearer token
103
108
  * @param {Object} [opts.payload] - JSON request body
104
109
  * @param {Object} [opts.dispatcher] - undici Dispatcher, the module's own agent when omitted
105
- * @param {AbortSignal} [opts.signal] - Aborts the request and any retry wait
110
+ * @param {AbortSignal} [opts.signal] - Aborts the request and any retry wait; without one the call is given `timeout` in all
111
+ * @param {number} [opts.timeout=DEFAULT_TIMEOUT] - Deadline in milliseconds for the whole call when no signal is given
106
112
  * @param {boolean} [opts.verbose] - Logs the request and the response to stderr
107
113
  * @returns {Promise<{data: Object, time: number}>} Parsed response body and the time the request took in milliseconds
108
114
  */
109
115
  async function apiRequest(url, opts) {
110
- const { method, apiToken, payload, dispatcher, signal, verbose } = opts;
116
+ const { method, apiToken, payload, dispatcher, verbose } = opts;
117
+ const signal = opts.signal || AbortSignal.timeout(opts.timeout || DEFAULT_TIMEOUT);
111
118
 
112
119
  const headers = {
113
120
  'User-Agent': `${packageData.name}/${packageData.version}`,
@@ -198,4 +205,4 @@ async function apiRequest(url, opts) {
198
205
  }
199
206
  }
200
207
 
201
- module.exports = { apiRequest, MAX_RESPONSE_SIZE };
208
+ module.exports = { apiRequest, MAX_RESPONSE_SIZE, DEFAULT_TIMEOUT };
@@ -3,7 +3,7 @@
3
3
  const libmime = require('libmime');
4
4
  const { htmlToText } = require('@postalsys/email-text-tools');
5
5
  const { apiRequest } = require('./api-request');
6
- const { estimateTokens, fitPrompt, DEFAULT_MAX_ALLOWED_TOKENS } = require('./token-estimate');
6
+ const { estimateTokens, fitPrompt, truncate, DEFAULT_MAX_ALLOWED_TOKENS } = require('./token-estimate');
7
7
  const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
8
8
  const { visibleHtml, visibleText } = require('./visible-text');
9
9
  const { authenticationBlock } = require('./authentication');
@@ -53,10 +53,25 @@ const FIRST_ONLY_HEADERS = new Set(['authentication-results']);
53
53
  // Headers that become their own property of the input object, under the same name
54
54
  const LIFTED_HEADERS = new Set(['subject', 'from', 'date']);
55
55
 
56
+ // Only the body is fitted to the token budget; everything else in the prompt has to be bounded
57
+ // on its own, or a subject or a References header long enough makes the prompt impossible to
58
+ // fit and the message goes unassessed. A header value is cut to what a reader would take in,
59
+ // the attachment list to the first entries, and both the name and the type of an attachment to
60
+ // what a file system allows
61
+ const MAX_HEADER_LENGTH = 1024;
62
+ const MAX_ATTACHMENTS = 20;
63
+ const MAX_ATTACHMENT_TEXT_LENGTH = 255;
64
+
56
65
  const SENTIMENTS = ['positive', 'neutral', 'negative'];
57
66
  const RISK_MIN = 1;
58
67
  const RISK_MAX = 5;
59
68
 
69
+ // Free text the model wrote is cut to a length no documented property needs: the summary is
70
+ // asked for in one sentence and so is the assessment, and text in the message can ask the model
71
+ // for more. The events and actions are what one message mentions
72
+ const MAX_TEXT_LENGTH = 1000;
73
+ const MAX_LIST_LENGTH = 50;
74
+
60
75
  // Request parameters a backend may refuse with a 400 that names them. Such a parameter is
61
76
  // dropped and the request repeated, and the refusal is remembered per endpoint and model so the
62
77
  // next call does not pay for it again. OpenAI's reasoning models reject the sampling parameters,
@@ -139,7 +154,7 @@ function asText(value) {
139
154
  }
140
155
 
141
156
  function headerText(value) {
142
- return libmime.decodeWords(asText(value)).replace(/\s+/g, ' ').trim();
157
+ return truncate(libmime.decodeWords(asText(value)).replace(/\s+/g, ' ').trim(), MAX_HEADER_LENGTH);
143
158
  }
144
159
 
145
160
  function headerKey(name) {
@@ -166,6 +181,19 @@ function optionalNumber(value) {
166
181
  return value === undefined || value === null || value === '' || isNaN(value) ? undefined : Number(value);
167
182
  }
168
183
 
184
+ // The name and type of an attachment as the model sees them, each cut, neither present when
185
+ // empty
186
+ function attachmentEntry(attachment) {
187
+ const entry = {};
188
+ for (const key of ['filename', 'contentType']) {
189
+ const value = truncate(attachment && attachment[key], MAX_ATTACHMENT_TEXT_LENGTH);
190
+ if (value) {
191
+ entry[key] = value;
192
+ }
193
+ }
194
+ return entry;
195
+ }
196
+
169
197
  /**
170
198
  * Builds the object the model is asked to analyze. Header values are decoded from their
171
199
  * RFC 2047 form, and the subject, sender and date get their own properties, which a value the
@@ -179,11 +207,13 @@ function optionalNumber(value) {
179
207
  function buildInput(message, allowedHeaders, trust) {
180
208
  const input = {
181
209
  subject: headerText(message.subject),
182
- from: formatAddress(message.from),
210
+ from: truncate(formatAddress(message.from), MAX_HEADER_LENGTH),
183
211
  date: formatDate(message.date),
184
212
  headers: {}
185
213
  };
186
214
 
215
+ // Repeated headers are joined as they come, and no further once the joined value has reached
216
+ // the cap: a header repeated a thousand times is not worth joining before it is cut
187
217
  const collected = new Map();
188
218
  for (const header of [].concat(message.headers || [])) {
189
219
  const key = headerKey(header && header.key);
@@ -191,24 +221,18 @@ function buildInput(message, allowedHeaders, trust) {
191
221
  continue;
192
222
  }
193
223
 
194
- const values = collected.get(key) || [];
195
- if (FIRST_ONLY_HEADERS.has(key) && values.length) {
196
- continue;
197
- }
198
-
199
224
  for (const value of [].concat(header.value)) {
200
225
  const text = headerText(value);
201
- if (text) {
202
- values.push(text);
226
+ const joined = collected.get(key);
227
+ if (!text || (joined && (FIRST_ONLY_HEADERS.has(key) || joined.length >= MAX_HEADER_LENGTH))) {
228
+ continue;
203
229
  }
204
- }
205
- if (values.length) {
206
- collected.set(key, values);
230
+ collected.set(key, joined ? `${joined}, ${text}` : text);
207
231
  }
208
232
  }
209
233
 
210
- for (const [key, values] of collected) {
211
- const value = FIRST_ONLY_HEADERS.has(key) ? values[0] : values.join(', ');
234
+ for (const [key, joined] of collected) {
235
+ const value = truncate(joined, MAX_HEADER_LENGTH);
212
236
  if (LIFTED_HEADERS.has(key)) {
213
237
  input[key] = value;
214
238
  } else if (key === 'authentication-results') {
@@ -225,8 +249,9 @@ function buildInput(message, allowedHeaders, trust) {
225
249
 
226
250
  input.attachments = []
227
251
  .concat(message.attachments || [])
228
- .map(attachment => ({ filename: attachment.filename, contentType: attachment.contentType }))
229
- .filter(attachment => attachment.filename || attachment.contentType);
252
+ .map(attachmentEntry)
253
+ .filter(entry => entry.filename || entry.contentType)
254
+ .slice(0, MAX_ATTACHMENTS);
230
255
 
231
256
  return input;
232
257
  }
@@ -270,8 +295,22 @@ function setOrDelete(obj, key, value) {
270
295
  }
271
296
  }
272
297
 
273
- function trimmed(value) {
274
- return typeof value === 'string' ? value.trim() : '';
298
+ function freeText(value) {
299
+ return typeof value === 'string' ? truncate(value.trim(), MAX_TEXT_LENGTH) : '';
300
+ }
301
+
302
+ // An event or an action. Its documented properties are all strings, a custom instruction set
303
+ // may add a number or a flag, and nothing nested is what a consumer expects to find in one
304
+ function normalizeEntry(entry) {
305
+ for (const key of Object.keys(entry)) {
306
+ const value = entry[key];
307
+ if (typeof value === 'string') {
308
+ setOrDelete(entry, key, freeText(value));
309
+ } else if (typeof value !== 'number' && typeof value !== 'boolean') {
310
+ delete entry[key];
311
+ }
312
+ }
313
+ return entry;
275
314
  }
276
315
 
277
316
  function toBoolean(value) {
@@ -305,7 +344,7 @@ function normalizeResult(values) {
305
344
  }
306
345
 
307
346
  if ('summary' in values) {
308
- setOrDelete(values, 'summary', trimmed(values.summary));
347
+ setOrDelete(values, 'summary', freeText(values.summary));
309
348
  }
310
349
 
311
350
  if ('shouldReply' in values) {
@@ -321,7 +360,7 @@ function normalizeResult(values) {
321
360
  if (Number.isFinite(risk)) {
322
361
  riskAssessment.risk = Math.min(RISK_MAX, Math.max(RISK_MIN, risk));
323
362
  if ('assessment' in riskAssessment) {
324
- setOrDelete(riskAssessment, 'assessment', trimmed(riskAssessment.assessment));
363
+ setOrDelete(riskAssessment, 'assessment', freeText(riskAssessment.assessment));
325
364
  }
326
365
  values.riskAssessment = riskAssessment;
327
366
  } else {
@@ -331,7 +370,12 @@ function normalizeResult(values) {
331
370
 
332
371
  for (const key of ['events', 'actions']) {
333
372
  if (key in values) {
334
- const list = [].concat(values[key]).filter(entry => entry && typeof entry === 'object' && !Array.isArray(entry));
373
+ const list = []
374
+ .concat(values[key])
375
+ .filter(entry => entry && typeof entry === 'object' && !Array.isArray(entry))
376
+ .slice(0, MAX_LIST_LENGTH)
377
+ .map(normalizeEntry)
378
+ .filter(entry => Object.keys(entry).length);
335
379
  setOrDelete(values, key, list.length ? list : null);
336
380
  }
337
381
  }
@@ -485,11 +529,19 @@ async function generateSummary(message, apiToken, opts) {
485
529
  const userMessage = bodyText => JSON.stringify(Object.assign({}, input, { text: bodyText }));
486
530
 
487
531
  // the budget covers both messages
488
- const { text: promptText, charactersRemoved } = fitPrompt({
489
- text,
490
- maxTokens: opts.maxTokens,
491
- overhead: [system === DEFAULT_SYSTEM_CONTENT ? DEFAULT_SYSTEM_TOKENS : system, userMessage('')]
492
- });
532
+ let promptText;
533
+ let charactersRemoved;
534
+ try {
535
+ ({ text: promptText, charactersRemoved } = fitPrompt({
536
+ text,
537
+ maxTokens: opts.maxTokens,
538
+ overhead: [system === DEFAULT_SYSTEM_CONTENT ? DEFAULT_SYSTEM_TOKENS : system, userMessage('')]
539
+ }));
540
+ } catch (err) {
541
+ // what the checks found is not lost with the answer
542
+ err.signals = signals;
543
+ throw err;
544
+ }
493
545
 
494
546
  const payload = {
495
547
  model,
@@ -21,6 +21,12 @@ const OPENAI_API_BASE_URL = 'https://api.openai.com';
21
21
  function getApiUrl(baseApiUrl, path) {
22
22
  let url = new URL(baseApiUrl || OPENAI_API_BASE_URL);
23
23
 
24
+ // The API is authenticated with the token, never with the URL. fetch() refuses a URL that
25
+ // carries credentials, and the error names the URL, so a password written there would end up
26
+ // in a log line
27
+ url.username = '';
28
+ url.password = '';
29
+
24
30
  let basePath = url.pathname.replace(/\/+$/, '');
25
31
  let requestPath = path || '/';
26
32
 
package/lib/signals.js CHANGED
@@ -3,7 +3,8 @@
3
3
  const { getDomain, parse: parseDomain } = require('tldts');
4
4
  const { domainToUnicode, domainToASCII } = require('url');
5
5
  const { authenticationFailed } = require('./authentication');
6
- const { INVISIBLE_CHARS } = require('./visible-text');
6
+ const { INVISIBLE_CHARS, MAX_LINK_TEXT_LENGTH } = require('./visible-text');
7
+ const { truncate } = require('./token-estimate');
7
8
 
8
9
  // Checks run in code on the message before the model sees it. Each one is a fact the email
9
10
  // cannot argue with: a model can be talked into a low score by text inside the message, code
@@ -80,6 +81,11 @@ const FLOORS = {
80
81
  const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/g;
81
82
  const DETAIL_LENGTH = 80;
82
83
 
84
+ // How many signals are listed, to the model and in the assessment. A message with thousands of
85
+ // executable attachments or mismatched links carries that many signals, each of them true, and
86
+ // the first few say everything the list would
87
+ const MAX_LISTED_SIGNALS = 20;
88
+
83
89
  const LATIN = /\p{Script=Latin}/u;
84
90
  // a letter that is not Latin: the negation of (non-letters and Latin letters)
85
91
  const NON_LATIN_LETTER = /[^\P{L}\p{Script=Latin}]/u;
@@ -150,14 +156,18 @@ function linkHost(href) {
150
156
  // Anchor text that names a host or URL itself, which a reader takes as the destination.
151
157
  // Trailing punctuation is not part of it. A host written as userinfo ("paypal.com@evil.example")
152
158
  // 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
159
+ // is dropped the way a browser drops it. The userinfo that is dropped is bounded: a local part is
160
+ // at most 64 octets (RFC 5321), and an unbounded run that backtracks for its "@" from every
161
+ // opening bracket in the text is quadratic
154
162
  const HOST_START = /(?:^|[\s(<"'[])(?:https?:\/\/)?/.source;
155
163
  const HOST = /((?:[\p{L}\p{N}-]+\.)+\p{L}{2,})/.source;
156
164
  const HOST_AS_USERINFO = new RegExp(`${HOST_START}${HOST}@`, 'iu');
157
- const HOST_IN_TEXT = new RegExp(`${HOST_START}(?:[^\\s/@]+@)?${HOST}(?=$|[\\s/?#:,.;!)\\]>"'])`, 'iu');
165
+ const HOST_IN_TEXT = new RegExp(`${HOST_START}(?:[^\\s/@]{1,64}@)?${HOST}(?=$|[\\s/?#:,.;!)\\]>"'])`, 'iu');
158
166
 
159
167
  function hostInText(text) {
160
- text = cleanText(text);
168
+ // cut before anything runs on it: the links of visibleHtml() are cut already, a caller's own
169
+ // may not be
170
+ text = cleanText(truncate(text, MAX_LINK_TEXT_LENGTH));
161
171
  const userinfo = HOST_AS_USERINFO.exec(text);
162
172
  if (userinfo && parseDomain(userinfo[1]).isIcann) {
163
173
  return userinfo[1].toLowerCase();
@@ -275,13 +285,18 @@ function collectSignals(message) {
275
285
  * @returns {Array<{code: string, detail: string}>}
276
286
  */
277
287
  function modelSignals(signals) {
278
- return signals.filter(signal => signal.floor > 0).map(({ code, detail }) => ({ code, detail }));
288
+ return signals
289
+ .filter(signal => signal.floor > 0)
290
+ .slice(0, MAX_LISTED_SIGNALS)
291
+ .map(({ code, detail }) => ({ code, detail }));
279
292
  }
280
293
 
281
294
  /**
282
295
  * Applies the signals to the model's answer: the risk score cannot be below their floor, and
283
296
  * the codes of the ones that carry one are listed with the assessment so a consumer sees what
284
- * was found
297
+ * was found. The list is always what the code found, an empty one when nothing did: the model
298
+ * writes the rest of the assessment, and text in the message can talk it into writing this
299
+ * field too, as facts no check established
285
300
  *
286
301
  * @param {Object} result - Normalized model output, changed in place
287
302
  * @param {Array} signals - As returned by collectSignals()
@@ -289,21 +304,25 @@ function modelSignals(signals) {
289
304
  */
290
305
  function applySignals(result, signals) {
291
306
  const scored = signals.filter(signal => signal.floor > 0);
292
- if (!scored.length) {
307
+ const hasAssessment = !!result.riskAssessment && typeof result.riskAssessment === 'object';
308
+ if (!scored.length && !hasAssessment) {
293
309
  return result;
294
310
  }
295
311
 
296
- const riskAssessment = result.riskAssessment && typeof result.riskAssessment === 'object' ? result.riskAssessment : {};
312
+ const riskAssessment = hasAssessment ? result.riskAssessment : {};
297
313
  const risk = Number.isFinite(riskAssessment.risk) ? riskAssessment.risk : 0;
298
- const floor = Math.max(...scored.map(signal => signal.floor));
314
+ const floor = scored.length ? Math.max(...scored.map(signal => signal.floor)) : 0;
299
315
 
300
316
  if (floor > risk) {
301
- const raised = scored.filter(signal => signal.floor > risk).map(signal => `${signal.code}: ${signal.detail}`);
317
+ const raised = scored
318
+ .filter(signal => signal.floor > risk)
319
+ .slice(0, MAX_LISTED_SIGNALS)
320
+ .map(signal => `${signal.code}: ${signal.detail}`);
302
321
  riskAssessment.risk = floor;
303
322
  riskAssessment.assessment = [riskAssessment.assessment, `Checks run on the message found: ${raised.join('; ')}.`].filter(Boolean).join(' ');
304
323
  }
305
324
 
306
- riskAssessment.signals = scored.map(signal => signal.code);
325
+ riskAssessment.signals = scored.slice(0, MAX_LISTED_SIGNALS).map(signal => signal.code);
307
326
  result.riskAssessment = riskAssessment;
308
327
  return result;
309
328
  }
@@ -87,6 +87,19 @@ function keepSurrogatePair(str, pos) {
87
87
  return pos;
88
88
  }
89
89
 
90
+ /**
91
+ * Cuts a string to at most `maxLength` UTF-16 code units, never between the halves of a
92
+ * surrogate pair
93
+ *
94
+ * @param {string} str
95
+ * @param {number} maxLength
96
+ * @returns {string}
97
+ */
98
+ function truncate(str, maxLength) {
99
+ str = (str || '').toString();
100
+ return str.length > maxLength ? str.substring(0, keepSurrogatePair(str, maxLength)) : str;
101
+ }
102
+
90
103
  /**
91
104
  * Cuts `text` so that it fits into `maxTokens` estimated tokens next to the fixed parts of the
92
105
  * prompt
@@ -122,10 +135,10 @@ function fitPrompt({ text, maxLength, maxTokens, overhead }) {
122
135
  throw error;
123
136
  }
124
137
 
125
- let fitted = text.length > maxLength ? text.substring(0, keepSurrogatePair(text, maxLength)) : text;
138
+ let fitted = truncate(text, maxLength);
126
139
  fitted = fitted.substring(0, fitLength(fitted, maxTokens - overheadTokens));
127
140
 
128
141
  return { text: fitted, charactersRemoved: text.length - fitted.length };
129
142
  }
130
143
 
131
- module.exports = { estimateTokens, fitLength, fitPrompt, DEFAULT_MAX_ALLOWED_TOKENS };
144
+ module.exports = { estimateTokens, fitLength, fitPrompt, truncate, DEFAULT_MAX_ALLOWED_TOKENS };
@@ -3,6 +3,7 @@
3
3
  const { parseDocument } = require('htmlparser2');
4
4
  const { default: serialize } = require('dom-serializer');
5
5
  const { isTag, isText, isComment, hasChildren, textContent, findAll, findOne, prependChild, removeElement } = require('domutils');
6
+ const { truncate } = require('./token-estimate');
6
7
 
7
8
  // What the reader never sees must not reach the model either: an email can carry instructions
8
9
  // for an AI in text a mail client does not render, and the summary has to describe the message
@@ -15,8 +16,16 @@ const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'title', 'iframe', '
15
16
  // Comments and quoted strings inside a style attribute, which carry no declarations
16
17
  const STYLE_NOISE = /\/\*[\s\S]*?\*\/|"[^"]*"|'[^']*'/g;
17
18
 
18
- // Outlook for Windows shows what a conditional comment wraps; the markers go, the content stays
19
- const CONDITIONAL_COMMENT = /<!--\[if [^\]]*\]>|<!\[endif\]-->/gi;
19
+ // Everything here runs synchronously in the process that called it, so how much of a message is
20
+ // read has to be this library's decision rather than the sender's. The HTML is cut before it is
21
+ // parsed; the text of a link is cut to what a reader could take in as its destination
22
+ const MAX_HTML_LENGTH = 1024 * 1024;
23
+ const MAX_LINK_TEXT_LENGTH = 1024;
24
+
25
+ // Outlook for Windows shows what a conditional comment wraps; the markers go, the content stays.
26
+ // The condition is bounded: an opening marker that never closes used to be scanned to the end
27
+ // of the document, once for every marker, which is quadratic
28
+ const CONDITIONAL_COMMENT = /<!--\[if [^\]]{0,200}\]>|<!\[endif\]-->/gi;
20
29
 
21
30
  // Characters that take no space on screen: zero-width joiners and spaces, soft hyphens, the
22
31
  // bidirectional controls and the word joiner. Removing them changes nothing the reader sees and
@@ -129,7 +138,7 @@ function linkText(node) {
129
138
  for (const image of findAll(child => child.name === 'img', node.children)) {
130
139
  parts.push(image.attribs.alt || '', image.attribs.title || '');
131
140
  }
132
- return parts.join(' ').replace(/\s+/g, ' ').trim();
141
+ return truncate(parts.join(' ').replace(/\s+/g, ' ').trim(), MAX_LINK_TEXT_LENGTH);
133
142
  }
134
143
 
135
144
  function collectLinks(document) {
@@ -166,7 +175,7 @@ function surfaceHead(document) {
166
175
  }
167
176
 
168
177
  function visibleHtml(html) {
169
- const document = parseDocument(String(html ?? '').replace(CONDITIONAL_COMMENT, ''));
178
+ const document = parseDocument(truncate(html, MAX_HTML_LENGTH).replace(CONDITIONAL_COMMENT, ''));
170
179
  const links = collectLinks(document);
171
180
  const stats = { hiddenElements: 0, invisibleCharacters: 0 };
172
181
  stripHidden(document, stats);
@@ -186,4 +195,4 @@ function visibleText(text) {
186
195
  return { text: matches ? text.replace(INVISIBLE_CHARS, '') : text, invisibleCharacters: matches ? matches.length : 0 };
187
196
  }
188
197
 
189
- module.exports = { visibleHtml, visibleText, INVISIBLE_CHARS };
198
+ module.exports = { visibleHtml, visibleText, INVISIBLE_CHARS, MAX_HTML_LENGTH, MAX_LINK_TEXT_LENGTH };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postalsys/email-ai-tools",
3
- "version": "2.2.2",
3
+ "version": "2.2.3",
4
4
  "description": "Summarize and risk-score email messages with an OpenAI-compatible chat model",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -3,7 +3,7 @@
3
3
  const { describe, it, before, after, beforeEach } = require('node:test');
4
4
  const assert = require('node:assert/strict');
5
5
  const { createMockServer, modelsResponse } = require('./helpers/mock-server');
6
- const { apiRequest, MAX_RESPONSE_SIZE } = require('../lib/api-request');
6
+ const { apiRequest, MAX_RESPONSE_SIZE, DEFAULT_TIMEOUT } = require('../lib/api-request');
7
7
 
8
8
  const HTML_502 = '<html><head><title>502 Bad Gateway</title></head><body><center><h1>502 Bad Gateway</h1></center></body></html>';
9
9
 
@@ -150,6 +150,13 @@ describe('apiRequest', () => {
150
150
  );
151
151
  });
152
152
 
153
+ it('gives up on a backend that never answers when the caller set no deadline', TIMEOUT, async () => {
154
+ mock.setHandler(() => new Promise(resolve => setTimeout(() => resolve(modelsResponse()), 2000).unref()));
155
+
156
+ await assert.rejects(() => apiRequest(url, { apiToken: 'token', timeout: 100 }), { name: 'TimeoutError' });
157
+ assert.ok(DEFAULT_TIMEOUT > 0 && DEFAULT_TIMEOUT <= 10 * 60 * 1000, 'the default is a few minutes');
158
+ });
159
+
153
160
  it('stops waiting for a 429 retry when the signal is aborted', TIMEOUT, async () => {
154
161
  mock.setHandler(() => ({ status: 429, raw: '', headers: { 'Retry-After': '10' } }));
155
162
 
@@ -44,6 +44,9 @@ describe('generateSummary', () => {
44
44
  riskAssessment: { risk: 1, assessment: 'Low risk message.' }
45
45
  };
46
46
 
47
+ // the same, with the signals list the code always writes
48
+ const expectedResult = Object.assign({}, summaryResult, { riskAssessment: Object.assign({}, summaryResult.riskAssessment, { signals: [] }) });
49
+
47
50
  const userObject = req => JSON.parse(req.body.messages[1].content);
48
51
 
49
52
  it('returns the model output as the result and the request usage beside it', async () => {
@@ -51,7 +54,7 @@ describe('generateSummary', () => {
51
54
 
52
55
  const { result, usage } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
53
56
 
54
- assert.deepEqual(result, summaryResult);
57
+ assert.deepEqual(result, expectedResult);
55
58
  assert.equal(usage.id, 'chatcmpl-abc');
56
59
  assert.equal(usage.model, DEFAULT_MODEL);
57
60
  assert.equal(usage.servedModel, 'gpt-6-luna-2026-09-22');
@@ -151,6 +154,74 @@ describe('generateSummary', () => {
151
154
  assert.equal(mock.requests[0].url, '/openai/v1/chat/completions');
152
155
  });
153
156
 
157
+ it('drops credentials written into the base URL rather than failing with them in the message', async () => {
158
+ mock.setHandler(() => chatResponse(summaryResult));
159
+
160
+ const { result } = await generateSummary(simpleMessage, 'my-api-key', { baseApiUrl: mock.url.replace('://', '://user:secret@') });
161
+
162
+ assert.deepEqual(result, expectedResult);
163
+ assert.equal(mock.requests[0].headers.authorization, 'Bearer my-api-key');
164
+ });
165
+
166
+ it('cuts header values and the attachment list so that no header can push the prompt over the budget', async () => {
167
+ mock.setHandler(() => chatResponse(summaryResult));
168
+
169
+ const cjk = size => '漢字仮名中文日本語文字'.repeat(Math.ceil(size / 11)).substring(0, size);
170
+ const references = [];
171
+ for (let i = 0; i < 2000; i++) {
172
+ references.push(`<message-${i}@example.com>`);
173
+ }
174
+ const attachments = [];
175
+ for (let i = 0; i < 500; i++) {
176
+ attachments.push({ filename: `${i}-${cjk(300)}.exe`, contentType: cjk(300) });
177
+ }
178
+
179
+ // A subject this long on its own used to be estimated over the default budget, and the
180
+ // message then went without any assessment at all
181
+ const { result, signals } = await generateSummary(
182
+ {
183
+ headers: [
184
+ { key: 'from', value: 'a@example.com' },
185
+ { key: 'subject', value: cjk(30000) },
186
+ { key: 'references', value: references },
187
+ { key: 'to', value: references.map(id => `${id.slice(1, -1)}`) }
188
+ ],
189
+ attachments,
190
+ text: 'Hi'
191
+ },
192
+ 'test-token',
193
+ { baseApiUrl: mock.url }
194
+ );
195
+
196
+ const input = userObject(mock.requests[0]);
197
+ assert.equal(input.subject.length, 1024);
198
+ assert.ok(input.headers.references.length <= 1024);
199
+ assert.ok(input.headers.to.length <= 1024);
200
+ assert.ok(input.headers.to.startsWith('message-0@example.com, message-1@example.com'));
201
+ assert.equal(input.attachments.length, 20);
202
+ assert.equal(input.attachments[0].filename.length, 255);
203
+ assert.equal(input.attachments[0].contentType.length, 255);
204
+ // every attachment is still checked, the model is told about the first few
205
+ assert.equal(signals.filter(signal => signal.code === 'executableAttachment').length, 500);
206
+ assert.equal(input.signals.length, 20);
207
+ assert.equal(result.riskAssessment.risk, 4);
208
+ });
209
+
210
+ it('cuts the subject, sender and date the caller supplies decoded', async () => {
211
+ mock.setHandler(() => chatResponse(summaryResult));
212
+
213
+ await generateSummary(
214
+ { subject: 'x'.repeat(5000), from: { name: 'n'.repeat(2000), address: `${'a'.repeat(2000)}@example.com` }, date: 'd'.repeat(5000), text: 'Hi' },
215
+ 'test-token',
216
+ { baseApiUrl: mock.url }
217
+ );
218
+
219
+ const input = userObject(mock.requests[0]);
220
+ assert.equal(input.subject.length, 1024);
221
+ assert.equal(input.from.length, 1024);
222
+ assert.equal(input.date.length, 1024);
223
+ });
224
+
154
225
  it('converts HTML to text when HTML is longer', async () => {
155
226
  mock.setHandler(() => chatResponse(summaryResult));
156
227
 
@@ -369,13 +440,51 @@ describe('generateSummary', () => {
369
440
  sentiment: 'positive',
370
441
  summary: 'Trimmed',
371
442
  shouldReply: true,
372
- riskAssessment: { risk: 5 },
443
+ riskAssessment: { risk: 5, signals: [] },
373
444
  events: [{ description: 'single event', startTime: '2026-10-02' }],
374
445
  language: 'et',
375
446
  emailType: 'inquiry'
376
447
  });
377
448
  });
378
449
 
450
+ it('cuts the free text the model wrote and keeps only flat values in events and actions', async () => {
451
+ const events = [];
452
+ for (let i = 0; i < 100; i++) {
453
+ events.push({ description: `event ${i}`, startTime: '2026-10-02' });
454
+ }
455
+ mock.setHandler(() =>
456
+ chatResponse({
457
+ summary: 'x'.repeat(5000),
458
+ riskAssessment: { risk: 2, assessment: 'y'.repeat(5000) },
459
+ events,
460
+ actions: [
461
+ { description: ` ${'z'.repeat(5000)} `, dueDate: '2026-10-03', priority: 1, done: false, nested: { a: 1 }, list: [1] },
462
+ { nested: {} }
463
+ ]
464
+ })
465
+ );
466
+
467
+ const { result } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
468
+
469
+ assert.equal(result.summary.length, 1000);
470
+ assert.equal(result.riskAssessment.assessment.length, 1000);
471
+ assert.equal(result.events.length, 50);
472
+ assert.deepEqual(result.actions, [{ description: 'z'.repeat(1000), dueDate: '2026-10-03', priority: 1, done: false }]);
473
+ });
474
+
475
+ // The list is documented as what the code found, so a model talked into writing one by text
476
+ // in the message must not get to hand a consumer facts no check established
477
+ it('replaces a signals list the model wrote with what the checks found', async () => {
478
+ mock.setHandler(() => chatResponse({ summary: 'x', riskAssessment: { risk: 1, signals: ['executableAttachment', 'authenticationFailed'] } }));
479
+
480
+ const benign = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
481
+ assert.deepEqual(benign.result.riskAssessment, { risk: 1, signals: [] });
482
+
483
+ const flagged = await generateSummary(Object.assign({ attachments: [{ filename: 'a.html' }] }, simpleMessage), 'test-token', { baseApiUrl: mock.url });
484
+ assert.deepEqual(flagged.result.riskAssessment.signals, ['scriptableAttachment']);
485
+ assert.equal(flagged.result.riskAssessment.risk, 3);
486
+ });
487
+
379
488
  it('drops documented properties that cannot be made to fit', async () => {
380
489
  mock.setHandler(() =>
381
490
  chatResponse({
@@ -398,7 +507,7 @@ describe('generateSummary', () => {
398
507
 
399
508
  const { result } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
400
509
 
401
- assert.deepEqual(result.riskAssessment, { risk: 3 });
510
+ assert.deepEqual(result.riskAssessment, { risk: 3, signals: [] });
402
511
  });
403
512
 
404
513
  it('extracts the JSON object from a response with surrounding text', async () => {
@@ -548,7 +657,7 @@ describe('generateSummary input checks', () => {
548
657
  assert.equal(input.text, 'Hello\npaypal');
549
658
  // what was removed is reported to the caller, not argued about with the model
550
659
  assert.ok(!('signals' in input));
551
- assert.deepEqual(result.riskAssessment, { risk: 1 });
660
+ assert.deepEqual(result.riskAssessment, { risk: 1, signals: [] });
552
661
  assert.deepEqual(
553
662
  signals.map(signal => signal.code),
554
663
  ['hiddenContent', 'invisibleCharacters']
@@ -44,4 +44,9 @@ describe('getApiUrl', () => {
44
44
  assert.equal(getApiUrl('https://api.example.com'), 'https://api.example.com/');
45
45
  assert.equal(getApiUrl('https://api.example.com/v1'), 'https://api.example.com/v1/');
46
46
  });
47
+
48
+ it('drops credentials written into the base URL, which fetch would echo in an error', () => {
49
+ assert.equal(getApiUrl('https://user:secret@proxy.example.com/v1', '/v1/models'), 'https://proxy.example.com/v1/models');
50
+ assert.equal(getApiUrl('https://user@proxy.example.com', '/v1/models'), 'https://proxy.example.com/v1/models');
51
+ });
47
52
  });
@@ -12,7 +12,7 @@ async function createMockServer() {
12
12
  req.on('data', chunk => {
13
13
  chunks.push(chunk);
14
14
  });
15
- req.on('end', () => {
15
+ req.on('end', async () => {
16
16
  const body = Buffer.concat(chunks).toString('utf-8');
17
17
  let parsedBody = null;
18
18
  try {
@@ -30,7 +30,8 @@ async function createMockServer() {
30
30
  body: parsedBody
31
31
  });
32
32
 
33
- const response = requestHandler(req, parsedBody);
33
+ // a handler may answer later, to stand in for a slow backend
34
+ const response = await requestHandler(req, parsedBody);
34
35
  if (typeof response.raw === 'string') {
35
36
  // a non-JSON body, for example an HTML error page from a proxy
36
37
  res.writeHead(response.status || 200, Object.assign({ 'Content-Type': 'text/html' }, response.headers));
@@ -3,9 +3,16 @@
3
3
  const { describe, it } = require('node:test');
4
4
  const assert = require('node:assert/strict');
5
5
  const { collectSignals, modelSignals, applySignals, isLookalikeHost, splitAddress } = require('../lib/signals');
6
+ const { MAX_LINK_TEXT_LENGTH } = require('../lib/visible-text');
6
7
 
7
8
  const codes = signals => signals.map(signal => signal.code);
8
9
 
10
+ function timeIt(fn) {
11
+ const start = process.hrtime.bigint();
12
+ fn();
13
+ return Number(process.hrtime.bigint() - start) / 1e6;
14
+ }
15
+
9
16
  describe('collectSignals', () => {
10
17
  it('finds nothing in an ordinary message', () => {
11
18
  const signals = collectSignals({
@@ -112,6 +119,32 @@ describe('collectSignals', () => {
112
119
  );
113
120
  });
114
121
 
122
+ it('reads a host out of link text in linear time, whatever the text is made of', { timeout: 5000 }, () => {
123
+ // Each shape used to make the host search backtrack from every bracket to the end of
124
+ // the text: 80 KB of the first took 1.8 s, and the time grew with the square of the size
125
+ const shapes = [size => '(a'.repeat(size / 2), size => '(a@'.repeat(size / 3), size => '('.repeat(size), size => '"a'.repeat(size / 2)];
126
+ for (const shape of shapes) {
127
+ const text = shape(1024 * 1024);
128
+ const ms = timeIt(() => collectSignals({ links: [{ href: 'https://evil.example/', text }] }));
129
+ assert.ok(ms < 200, `took ${ms} ms`);
130
+ }
131
+ });
132
+
133
+ it('reads the host off the start of the link text, which is cut to what a reader takes in', () => {
134
+ const padding = 'x'.repeat(MAX_LINK_TEXT_LENGTH);
135
+ const signals = collectSignals({
136
+ links: [
137
+ { href: 'https://evil.example/', text: `paypal.com ${padding}` },
138
+ { href: 'https://evil2.example/', text: `${padding} paypal.com` }
139
+ ]
140
+ });
141
+
142
+ assert.deepEqual(
143
+ signals.map(signal => signal.detail),
144
+ ['link text says "paypal.com", the target is "evil.example"']
145
+ );
146
+ });
147
+
115
148
  it('flags a lookalike domain written with mixed scripts, in unicode, punycode or percent encoding', () => {
116
149
  assert.equal(isLookalikeHost('p\u0430ypal.com'), true);
117
150
  assert.equal(isLookalikeHost('xn--pypal-4ve.com'), true);
@@ -152,6 +185,18 @@ describe('collectSignals', () => {
152
185
  assert.deepEqual(modelSignals([{ code: 'executableAttachment', detail: '"a.exe"', floor: 4 }]), [{ code: 'executableAttachment', detail: '"a.exe"' }]);
153
186
  });
154
187
 
188
+ it('lists at most twenty signals to the model, however many a message carries', () => {
189
+ const attachments = [];
190
+ for (let i = 0; i < 100; i++) {
191
+ attachments.push({ filename: `file${i}.exe` });
192
+ }
193
+ const signals = collectSignals({ attachments });
194
+
195
+ assert.equal(signals.length, 100, 'every attachment is checked');
196
+ assert.equal(modelSignals(signals).length, 20);
197
+ assert.equal(modelSignals(signals)[0].detail, '"file0.exe"');
198
+ });
199
+
155
200
  it('splits "Name <address>" and a bare address', () => {
156
201
  assert.deepEqual(splitAddress('"Jane Doe" <jane@example.com>'), { name: 'Jane Doe', address: 'jane@example.com' });
157
202
  assert.deepEqual(splitAddress('jane@example.com'), { name: '', address: 'jane@example.com' });
@@ -186,9 +231,34 @@ describe('applySignals', () => {
186
231
  });
187
232
  });
188
233
 
189
- it('leaves a result alone when nothing scored', () => {
234
+ it('lists nothing when nothing scored, and leaves a result without an assessment alone', () => {
190
235
  const result = applySignals({ summary: 'x', riskAssessment: { risk: 1 } }, [{ code: 'hiddenContent', detail: '1', floor: 0 }]);
236
+ assert.deepEqual(result, { summary: 'x', riskAssessment: { risk: 1, signals: [] } });
237
+
238
+ assert.deepEqual(applySignals({ summary: 'x' }, []), { summary: 'x' });
239
+ });
191
240
 
192
- assert.deepEqual(result, { summary: 'x', riskAssessment: { risk: 1 } });
241
+ // The list is documented as what the code found. A model talked into writing one by text in
242
+ // the message would otherwise hand a consumer facts no check established, or an empty list
243
+ // that reads as "nothing found" on a message the checks never got to speak about
244
+ it('replaces whatever signals the model listed with what the checks found', () => {
245
+ const forged = () => ({ riskAssessment: { risk: 1, signals: ['executableAttachment', 'authenticationFailed'] } });
246
+
247
+ assert.deepEqual(applySignals(forged(), []).riskAssessment.signals, []);
248
+ assert.deepEqual(applySignals(forged(), [{ code: 'hiddenContent', detail: '1', floor: 0 }]).riskAssessment.signals, []);
249
+ assert.deepEqual(applySignals(forged(), [{ code: 'replyToMismatch', detail: 'd', floor: 2 }]).riskAssessment.signals, ['replyToMismatch']);
250
+ });
251
+
252
+ it('lists at most twenty signals in the result and in the assessment', () => {
253
+ const signals = [];
254
+ for (let i = 0; i < 100; i++) {
255
+ signals.push({ code: 'executableAttachment', detail: `"file${i}.exe"`, floor: 4 });
256
+ }
257
+ const result = applySignals({ riskAssessment: { risk: 1 } }, signals);
258
+
259
+ assert.equal(result.riskAssessment.risk, 4);
260
+ assert.equal(result.riskAssessment.signals.length, 20);
261
+ assert.ok(result.riskAssessment.assessment.includes('"file19.exe"'));
262
+ assert.ok(!result.riskAssessment.assessment.includes('"file20.exe"'));
193
263
  });
194
264
  });
@@ -3,7 +3,7 @@
3
3
  const { describe, it, before, after, beforeEach } = require('node:test');
4
4
  const assert = require('node:assert/strict');
5
5
  const { createMockServer, chatResponse } = require('./helpers/mock-server');
6
- const { estimateTokens, fitLength, fitPrompt } = require('../lib/token-estimate');
6
+ const { estimateTokens, fitLength, fitPrompt, truncate } = require('../lib/token-estimate');
7
7
  const { generateSummary } = require('..');
8
8
 
9
9
  // 64 KB of CJK text with no whitespace or punctuation, the input that made the old tokenizer
@@ -47,6 +47,14 @@ describe('token estimate', () => {
47
47
  }
48
48
  });
49
49
 
50
+ it('truncate cuts to the length without splitting a surrogate pair, and takes any input', () => {
51
+ assert.equal(truncate(`${'a'.repeat(9)}\u{1F600}b`, 10), 'a'.repeat(9));
52
+ assert.equal(truncate(`${'a'.repeat(9)}\u{1F600}b`, 11), `${'a'.repeat(9)}\u{1F600}`);
53
+ assert.equal(truncate('short', 10), 'short');
54
+ assert.equal(truncate(undefined, 10), '');
55
+ assert.equal(truncate(12345, 3), '123');
56
+ });
57
+
50
58
  it('fits a 64 KB CJK body in well under 100 ms', () => {
51
59
  const text = cjk(64 * 1024);
52
60
  const ms = timeIt(() => fitLength(text, 18000), 1);
@@ -142,10 +150,15 @@ describe('prompt fitting', () => {
142
150
  assert.equal(usage.text, 'Short message');
143
151
  });
144
152
 
145
- it('generateSummary throws PROMPT_TOO_LONG when the prompt alone exceeds the limit', async () => {
146
- await assert.rejects(() => generateSummary({ headers: [], text: 'hello' }, 'token', { baseApiUrl: mock.url, maxTokens: 50 }), {
147
- code: 'PROMPT_TOO_LONG'
148
- });
153
+ it('generateSummary throws PROMPT_TOO_LONG when the prompt alone exceeds the limit, with what the checks found', async () => {
154
+ await assert.rejects(
155
+ () => generateSummary({ headers: [], attachments: [{ filename: 'a.exe' }], text: 'hello' }, 'token', { baseApiUrl: mock.url, maxTokens: 50 }),
156
+ err => {
157
+ assert.equal(err.code, 'PROMPT_TOO_LONG');
158
+ assert.equal(err.signals[0].code, 'executableAttachment');
159
+ return true;
160
+ }
161
+ );
149
162
  assert.equal(mock.requests.length, 0);
150
163
  });
151
164
  });
@@ -2,9 +2,15 @@
2
2
 
3
3
  const { describe, it } = require('node:test');
4
4
  const assert = require('node:assert/strict');
5
- const { visibleHtml, visibleText } = require('../lib/visible-text');
5
+ const { visibleHtml, visibleText, MAX_HTML_LENGTH, MAX_LINK_TEXT_LENGTH } = require('../lib/visible-text');
6
6
  const { htmlToText } = require('@postalsys/email-text-tools');
7
7
 
8
+ function timeIt(fn) {
9
+ const start = process.hrtime.bigint();
10
+ fn();
11
+ return Number(process.hrtime.bigint() - start) / 1e6;
12
+ }
13
+
8
14
  describe('visibleHtml', () => {
9
15
  it('drops what a mail client does not show, and counts the styled-away elements that carried text', () => {
10
16
  const result = visibleHtml(
@@ -94,6 +100,31 @@ describe('visibleHtml', () => {
94
100
  assert.equal(result.html(), '');
95
101
  }
96
102
  });
103
+
104
+ it('strips conditional comment markers in linear time when they never close', { timeout: 5000 }, () => {
105
+ // An opening marker with no "]>" after it used to be scanned to the end of the document,
106
+ // once per marker: 64 KB of them took 180 ms and a megabyte would have taken most of a
107
+ // minute, in the main process of the application
108
+ const html = '<!--[if '.repeat(MAX_HTML_LENGTH / 8);
109
+ const ms = timeIt(() => visibleHtml(html));
110
+ assert.ok(ms < 1000, `took ${ms} ms`);
111
+
112
+ const far = visibleHtml(`<!--[if ${'x'.repeat(MAX_HTML_LENGTH - 16)}]><p>never shown</p>`);
113
+ assert.equal(far.html(), '');
114
+ });
115
+
116
+ it('reads no more than a megabyte of HTML', () => {
117
+ const result = visibleHtml(`<p>${'a'.repeat(MAX_HTML_LENGTH)}</p><a href="https://evil.example/">paypal.com</a>`);
118
+
119
+ assert.deepEqual(result.links, []);
120
+ assert.equal(htmlToText(result.html()).length, MAX_HTML_LENGTH - 3);
121
+ });
122
+
123
+ it('cuts the text of a link to what a reader takes in', () => {
124
+ const { links } = visibleHtml(`<a href="https://a.example/">${'a'.repeat(MAX_LINK_TEXT_LENGTH + 100)}</a>`);
125
+
126
+ assert.equal(links[0].text.length, MAX_LINK_TEXT_LENGTH);
127
+ });
97
128
  });
98
129
 
99
130
  describe('visibleText', () => {