@postalsys/email-ai-tools 2.2.8 → 2.3.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/cjs/index.d.ts +28 -0
  4. package/dist/cjs/index.js +67 -0
  5. package/dist/cjs/lib/api-request.d.ts +42 -0
  6. package/dist/cjs/lib/api-request.js +183 -0
  7. package/dist/cjs/lib/authentication.d.ts +46 -0
  8. package/{lib → dist/cjs/lib}/authentication.js +33 -44
  9. package/dist/cjs/lib/generate-summary.d.ts +143 -0
  10. package/dist/cjs/lib/generate-summary.js +562 -0
  11. package/dist/cjs/lib/get-api-url.d.ts +19 -0
  12. package/dist/cjs/lib/get-api-url.js +37 -0
  13. package/dist/cjs/lib/list-models.d.ts +46 -0
  14. package/dist/cjs/lib/list-models.js +125 -0
  15. package/dist/cjs/lib/signals.d.ts +72 -0
  16. package/dist/cjs/lib/signals.js +293 -0
  17. package/dist/cjs/lib/token-estimate.d.ts +46 -0
  18. package/{lib → dist/cjs/lib}/token-estimate.js +21 -50
  19. package/dist/cjs/lib/visible-text.d.ts +33 -0
  20. package/dist/cjs/lib/visible-text.js +182 -0
  21. package/dist/cjs/package-info.d.ts +2 -0
  22. package/dist/cjs/package-info.js +6 -0
  23. package/dist/cjs/package.json +3 -0
  24. package/dist/esm/index.d.ts +28 -0
  25. package/dist/esm/index.js +30 -0
  26. package/dist/esm/lib/api-request.d.ts +42 -0
  27. package/{lib → dist/esm/lib}/api-request.js +20 -53
  28. package/dist/esm/lib/authentication.d.ts +46 -0
  29. package/dist/esm/lib/authentication.js +149 -0
  30. package/dist/esm/lib/generate-summary.d.ts +143 -0
  31. package/{lib → dist/esm/lib}/generate-summary.js +59 -155
  32. package/dist/esm/lib/get-api-url.d.ts +19 -0
  33. package/{lib → dist/esm/lib}/get-api-url.js +4 -13
  34. package/dist/esm/lib/list-models.d.ts +46 -0
  35. package/{lib → dist/esm/lib}/list-models.js +19 -50
  36. package/dist/esm/lib/signals.d.ts +72 -0
  37. package/{lib → dist/esm/lib}/signals.js +33 -79
  38. package/dist/esm/lib/token-estimate.d.ts +46 -0
  39. package/dist/esm/lib/token-estimate.js +108 -0
  40. package/dist/esm/lib/visible-text.d.ts +33 -0
  41. package/{lib → dist/esm/lib}/visible-text.js +14 -40
  42. package/dist/esm/package-info.d.ts +2 -0
  43. package/dist/esm/package-info.js +3 -0
  44. package/dist/esm/package.json +3 -0
  45. package/package.json +63 -10
  46. package/.github/VULNERABILITY_REPORT.yml +0 -75
  47. package/.github/workflows/release.yaml +0 -37
  48. package/.github/workflows/test.yaml +0 -35
  49. package/.ncurc.js +0 -23
  50. package/.prettierignore +0 -5
  51. package/.prettierrc.js +0 -10
  52. package/.release-please-manifest.json +0 -3
  53. package/CLAUDE.md +0 -185
  54. package/eslint.config.js +0 -70
  55. package/examples/fixtures/message-1.json +0 -74
  56. package/examples/list-models.js +0 -14
  57. package/examples/summary.js +0 -34
  58. package/index.js +0 -26
  59. package/release-please-config.json +0 -10
  60. package/test/api-request.test.js +0 -169
  61. package/test/authentication.test.js +0 -110
  62. package/test/commonjs-graph.test.js +0 -21
  63. package/test/dispatcher.test.js +0 -94
  64. package/test/generate-summary.test.js +0 -795
  65. package/test/get-api-url.test.js +0 -52
  66. package/test/helpers/mock-server.js +0 -120
  67. package/test/index.test.js +0 -57
  68. package/test/list-models.test.js +0 -302
  69. package/test/signals.test.js +0 -264
  70. package/test/token-estimate.test.js +0 -164
  71. package/test/visible-text.test.js +0 -144
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listModels = listModels;
4
+ exports.describeModel = describeModel;
5
+ exports.nonChatModelPattern = nonChatModelPattern;
6
+ const api_request_js_1 = require("./api-request.js");
7
+ const get_api_url_js_1 = require("./get-api-url.js");
8
+ const OPENAI_API_MODELS = '/v1/models';
9
+ const OPENAI_API_HOST = new URL(get_api_url_js_1.OPENAI_API_BASE_URL).hostname;
10
+ // On OpenAI's own endpoint the names are known, and these are not chat models: embeddings,
11
+ // speech, images, video, moderation, the legacy completion models, and the chat models that are
12
+ // specialised for something else
13
+ const OPENAI_NON_CHAT_MODEL = /embedding|tts|whisper|transcribe|dall-e|image|realtime|^gpt-live|audio|moderation|babbage|davinci|sora|instruct|codex|search|computer-use|cyber|daybreak|rosalind/i;
14
+ // Elsewhere the names are whatever the operator pulled ("Llama-3.1-8B-Instruct" is a chat model
15
+ // there), so only the unmistakable ones are left out
16
+ const GENERIC_NON_CHAT_MODEL = /embed|whisper|tts|rerank/i;
17
+ const DATED_SNAPSHOT = /-\d{4}-\d{2}-\d{2}$|-\d{4,}$/;
18
+ // What a model is good for, by family, for a picker that shows more than a name. Recommended
19
+ // marks the ones that suit email triage: capable enough for it and cheap enough to run on every
20
+ // message. Prices change, so the notes stay qualitative
21
+ const MODEL_NOTES = [
22
+ [/^gpt-6-luna/, 'Fast and inexpensive, built for high-volume work like this', true],
23
+ [/^gpt-6(?:\.\d+)?-sol/, 'Mid-priced reasoning model', true],
24
+ [/^gpt-6-astra/, 'Most capable and most expensive', false],
25
+ [/^gpt-5\.6-luna/, 'Inexpensive, previous generation', true],
26
+ [/^gpt-5\.6-terra/, 'Mid-priced, previous generation', false],
27
+ [/^gpt-5\.6-sol/, 'Expensive, previous generation', false],
28
+ [/-nano/, 'Smallest and cheapest of its generation', true],
29
+ [/-mini/, 'Small and inexpensive', true],
30
+ [/-pro/, 'Premium reasoning, very expensive', false],
31
+ [/^gpt-5(?:\.\d+)?$/, 'Full-size reasoning model of its generation', false],
32
+ [/^gpt-4\.1|^gpt-4o/, 'Previous generation without reasoning', false],
33
+ [/^o\d/, 'Earlier reasoning series', false],
34
+ [/chat/, 'Conversational model, not a reasoning model', false],
35
+ [/^gpt-oss/, 'Open-weight reasoning model', false]
36
+ ];
37
+ /**
38
+ * A short note on a model and whether it suits email triage
39
+ *
40
+ * @param input - Model name
41
+ * @returns An empty description for a name nothing is known about
42
+ */
43
+ function describeModel(input) {
44
+ const id = String(input ?? '');
45
+ const dated = DATED_SNAPSHOT.test(id);
46
+ for (const [pattern, description, recommended] of MODEL_NOTES) {
47
+ if (pattern.test(id)) {
48
+ return { description: dated ? `${description}, pinned snapshot` : description, recommended: recommended && !dated };
49
+ }
50
+ }
51
+ return { description: dated ? 'Pinned snapshot' : '', recommended: false };
52
+ }
53
+ const collator = new Intl.Collator('en', { numeric: true });
54
+ function isOpenAiEndpoint(baseApiUrl) {
55
+ return new URL(baseApiUrl || get_api_url_js_1.OPENAI_API_BASE_URL).hostname === OPENAI_API_HOST;
56
+ }
57
+ /**
58
+ * The pattern of model names listModels() leaves out for an endpoint
59
+ *
60
+ * @param baseApiUrl - Base API URL (default: OpenAI API)
61
+ */
62
+ function nonChatModelPattern(baseApiUrl) {
63
+ return isOpenAiEndpoint(baseApiUrl) ? OPENAI_NON_CHAT_MODEL : GENERIC_NON_CHAT_MODEL;
64
+ }
65
+ // Sort key: GPT families first, newest first, then the o-series, then everything else; within a
66
+ // family the plain name before dated snapshots and previews
67
+ function decorate(entry) {
68
+ const match = /^(gpt-|o)(\d+(?:\.\d+)?)/i.exec(entry.id);
69
+ return {
70
+ entry,
71
+ group: match ? (match[1].toLowerCase() === 'o' ? 1 : 0) : 2,
72
+ version: match ? parseFloat(match[2]) : 0,
73
+ dated: DATED_SNAPSHOT.test(entry.id),
74
+ preview: /preview/i.test(entry.id)
75
+ };
76
+ }
77
+ function compare(a, b) {
78
+ return (a.group - b.group ||
79
+ b.version - a.version ||
80
+ Number(a.dated) - Number(b.dated) ||
81
+ Number(a.preview) - Number(b.preview) ||
82
+ collator.compare(a.entry.id, b.entry.id));
83
+ }
84
+ function formatName(id) {
85
+ return id
86
+ .replace(/-/g, ' ')
87
+ .replace(/^.| ./g, c => c.toUpperCase())
88
+ .replace(/\bhd\b/gi, c => c.toUpperCase())
89
+ .replace(/\b\d+k\b/gi, c => c.toUpperCase())
90
+ .replace(/Dall E/g, 'Dall-E')
91
+ .replace(/^Whisper /g, 'Whisper-')
92
+ .replace(/(\d{4}) (\d{2}) (\d{2})/g, (o, y, m, d) => `${y}-${m}-${d}`)
93
+ .replace(/^(gpt|tts)\s/gi, (o, n) => `${n.toUpperCase()}-`);
94
+ }
95
+ /**
96
+ * Lists the models the API endpoint serves, newest family first, with a display name for each
97
+ *
98
+ * @param apiToken - API authentication token
99
+ */
100
+ async function listModels(apiToken, opts) {
101
+ opts = opts || {};
102
+ const baseApiUrl = opts.baseApiUrl || get_api_url_js_1.OPENAI_API_BASE_URL;
103
+ const { data, time } = await (0, api_request_js_1.apiRequest)((0, get_api_url_js_1.getApiUrl)(baseApiUrl, OPENAI_API_MODELS), {
104
+ method: 'get',
105
+ apiToken,
106
+ dispatcher: opts.dispatcher,
107
+ signal: opts.signal,
108
+ verbose: opts.verbose
109
+ });
110
+ const nonChat = nonChatModelPattern(baseApiUrl);
111
+ // the notes are about OpenAI's names; another endpoint's "mini" is whatever its operator pulled
112
+ const describe = isOpenAiEndpoint(baseApiUrl) ? describeModel : () => ({ description: '', recommended: false });
113
+ const response = {
114
+ models: []
115
+ .concat((data && data.data) || [])
116
+ .filter((entry) => entry && typeof entry.id === 'string' && entry.id && entry.owned_by !== 'openai-dev' && (opts.chatOnly === false || !nonChat.test(entry.id)))
117
+ .map(decorate)
118
+ .sort(compare)
119
+ .map(({ entry }) => Object.assign(entry, { name: formatName(entry.id) }, describe(entry.id)))
120
+ };
121
+ if (opts.verbose) {
122
+ response._time = time;
123
+ }
124
+ return response;
125
+ }
@@ -0,0 +1,72 @@
1
+ import type { AuthenticationBlock } from './authentication.js';
2
+ import type { MessageLink } from './visible-text.js';
3
+ /** A fact established by a check run in code */
4
+ export interface Signal {
5
+ code: string;
6
+ detail: string;
7
+ /** The least risk score a message carrying the signal gets, 0 for one that is only reported */
8
+ floor: number;
9
+ }
10
+ /** What collectSignals() checks */
11
+ export interface SignalInput {
12
+ /** Sender as "Name <address>" */
13
+ from?: string | null | undefined;
14
+ /** Reply-To as "Name <address>" */
15
+ replyTo?: string | null | undefined;
16
+ /** Attachments with filename and contentType */
17
+ attachments?: Array<{
18
+ filename?: unknown;
19
+ contentType?: unknown;
20
+ } | null | undefined> | null | undefined;
21
+ /** Every link of the HTML, from visibleHtml() */
22
+ links?: MessageLink[] | null | undefined;
23
+ /** Text body, read for links when there is no HTML */
24
+ text?: string | null | undefined;
25
+ /** As returned by authenticationBlock() */
26
+ authentication?: AuthenticationBlock | null | undefined;
27
+ /** Hidden elements removed from the HTML */
28
+ hiddenElements?: number | undefined;
29
+ /** Invisible characters removed */
30
+ invisibleCharacters?: number | undefined;
31
+ }
32
+ /** The part of the model's answer the signals apply to */
33
+ export interface RiskResult {
34
+ riskAssessment?: {
35
+ risk?: number;
36
+ assessment?: string;
37
+ signals?: string[];
38
+ [key: string]: unknown;
39
+ } | undefined;
40
+ [key: string]: unknown;
41
+ }
42
+ declare function splitAddress(input: unknown): {
43
+ name: string;
44
+ address: string;
45
+ };
46
+ declare function isLookalikeHost(host: unknown): boolean;
47
+ /**
48
+ * Runs the checks on a message
49
+ */
50
+ declare function collectSignals(message: SignalInput): Signal[];
51
+ /**
52
+ * The signals the model gets to see: the ones that carry a floor, without it
53
+ *
54
+ * @param signals - As returned by collectSignals()
55
+ */
56
+ declare function modelSignals(signals: Signal[]): Array<{
57
+ code: string;
58
+ detail: string;
59
+ }>;
60
+ /**
61
+ * Applies the signals to the model's answer: the risk score cannot be below their floor, and
62
+ * the codes of the ones that carry one are listed with the assessment so a consumer sees what
63
+ * was found. The list is always what the code found, an empty one when nothing did: the model
64
+ * writes the rest of the assessment, and text in the message can talk it into writing this
65
+ * field too, as facts no check established
66
+ *
67
+ * @param result - Normalized model output, changed in place
68
+ * @param signals - As returned by collectSignals()
69
+ * @returns The same result
70
+ */
71
+ declare function applySignals<T extends RiskResult>(result: T, signals: Signal[]): T;
72
+ export { collectSignals, modelSignals, applySignals, isLookalikeHost, splitAddress };
@@ -0,0 +1,293 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.collectSignals = collectSignals;
7
+ exports.modelSignals = modelSignals;
8
+ exports.applySignals = applySignals;
9
+ exports.isLookalikeHost = isLookalikeHost;
10
+ exports.splitAddress = splitAddress;
11
+ const tldts_1 = require("tldts");
12
+ const node_url_1 = __importDefault(require("node:url"));
13
+ const authentication_js_1 = require("./authentication.js");
14
+ const visible_text_js_1 = require("./visible-text.js");
15
+ const token_estimate_js_1 = require("./token-estimate.js");
16
+ // Checks run in code on the message before the model sees it. Each one is a fact the email
17
+ // cannot argue with: a model can be talked into a low score by text inside the message, code
18
+ // cannot. The floor is the least risk score a message carrying the signal gets, whatever the
19
+ // model says. A signal with no floor is only reported to the caller
20
+ // Files that run when opened. Double extensions ("invoice.pdf.exe") end in one of these too
21
+ const EXECUTABLE_EXTENSIONS = new Set([
22
+ 'exe',
23
+ 'scr',
24
+ 'pif',
25
+ 'com',
26
+ 'bat',
27
+ 'cmd',
28
+ 'vbs',
29
+ 'vbe',
30
+ 'js',
31
+ 'jse',
32
+ 'wsf',
33
+ 'wsh',
34
+ 'ws',
35
+ 'sct',
36
+ 'ps1',
37
+ 'psm1',
38
+ 'msi',
39
+ 'msp',
40
+ 'msix',
41
+ 'appx',
42
+ 'hta',
43
+ 'cpl',
44
+ 'reg',
45
+ 'lnk',
46
+ 'url',
47
+ 'scf',
48
+ 'inf',
49
+ 'chm',
50
+ 'xll',
51
+ 'jar',
52
+ 'apk',
53
+ 'iso',
54
+ 'img',
55
+ 'vhd',
56
+ 'vhdx',
57
+ 'dll',
58
+ 'settingcontent-ms',
59
+ 'library-ms'
60
+ ]);
61
+ const EXECUTABLE_TYPES = new Set([
62
+ 'application/x-msdownload',
63
+ 'application/x-msdos-program',
64
+ 'application/x-ms-installer',
65
+ 'application/vnd.microsoft.portable-executable',
66
+ 'application/x-dosexec',
67
+ 'application/x-executable'
68
+ ]);
69
+ // Files a mail client or browser runs code from when opened
70
+ const SCRIPTABLE_EXTENSIONS = new Set(['html', 'htm', 'shtml', 'xhtml', 'xht', 'svg', 'one']);
71
+ const FLOORS = {
72
+ executableAttachment: 4,
73
+ lookalikeDomain: 4,
74
+ linkTargetMismatch: 3,
75
+ scriptableAttachment: 3,
76
+ displayNameAddressMismatch: 3,
77
+ authenticationFailed: 3,
78
+ replyToMismatch: 2
79
+ };
80
+ // A detail is attacker-written text that lands in the assessment and in front of the model, so
81
+ // it is cleaned of anything that could reorder or hide it, cut short and quoted
82
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/g;
83
+ const DETAIL_LENGTH = 80;
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
+ const LATIN = /\p{Script=Latin}/u;
89
+ // a letter that is not Latin: the negation of (non-letters and Latin letters)
90
+ const NON_LATIN_LETTER = /[^\P{L}\p{Script=Latin}]/u;
91
+ function cleanText(value) {
92
+ return String(value ?? '')
93
+ .normalize('NFKC')
94
+ .replace(CONTROL_CHARS, '')
95
+ .replace(visible_text_js_1.INVISIBLE_CHARS, '')
96
+ .replace(/\s+/g, ' ')
97
+ .trim();
98
+ }
99
+ function quoted(value) {
100
+ const text = cleanText(value);
101
+ return `"${text.length > DETAIL_LENGTH ? `${text.substring(0, DETAIL_LENGTH)}...` : text}"`;
102
+ }
103
+ function registrableDomain(input) {
104
+ const host = node_url_1.default.domainToASCII(String(input ?? '').toLowerCase()) || String(input ?? '').toLowerCase();
105
+ return (0, tldts_1.getDomain)(host) || host || null;
106
+ }
107
+ function addressDomain(address) {
108
+ const match = /@([^\s>@]+)\s*>?\s*$/.exec(String(address ?? ''));
109
+ return match ? registrableDomain(match[1]) : null;
110
+ }
111
+ // "Name <address>" or a bare address, as the From and Reply-To values are formatted
112
+ function splitAddress(input) {
113
+ const value = String(input ?? '').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
+ // A label is a lookalike when it mixes Latin letters with letters of another script: "paypal"
121
+ // spelled with a Cyrillic "a" reads as the brand and resolves elsewhere. A label written entirely in
122
+ // another script is a normal internationalised name
123
+ function isLookalikeHost(host) {
124
+ return node_url_1.default
125
+ .domainToUnicode(String(host ?? ''))
126
+ .split('.')
127
+ .some(label => LATIN.test(label) && NON_LATIN_LETTER.test(label));
128
+ }
129
+ // The host a browser would connect to: tabs and newlines are dropped, leading and trailing
130
+ // controls and spaces stripped, a scheme-relative or backslashed form resolved, the host
131
+ // lower-cased, percent-decoded and punycoded, all by the URL parser. Only http and https count
132
+ function linkHost(input) {
133
+ const href = String(input ?? '')
134
+ .replace(/[\t\n\r]/g, '')
135
+ .replace(/^[\u0000- ]+|[\u0000- ]+$/g, '');
136
+ let parsed;
137
+ try {
138
+ parsed = new URL(href, 'https://base.invalid/');
139
+ }
140
+ catch {
141
+ return null;
142
+ }
143
+ if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || parsed.hostname === 'base.invalid') {
144
+ return null;
145
+ }
146
+ return parsed.hostname;
147
+ }
148
+ // Anchor text that names a host or URL itself, which a reader takes as the destination.
149
+ // Trailing punctuation is not part of it. A host written as userinfo ("paypal.com@evil.example")
150
+ // is what the reader takes in first, so it counts when it is a real name; otherwise the userinfo
151
+ // is dropped the way a browser drops it. The userinfo that is dropped is bounded: a local part is
152
+ // at most 64 octets (RFC 5321), and an unbounded run that backtracks for its "@" from every
153
+ // opening bracket in the text is quadratic
154
+ const HOST_START = /(?:^|[\s(<"'[])(?:https?:\/\/)?/.source;
155
+ const HOST = /((?:[\p{L}\p{N}-]+\.)+\p{L}{2,})/u.source;
156
+ const HOST_AS_USERINFO = new RegExp(`${HOST_START}${HOST}@`, 'iu');
157
+ const HOST_IN_TEXT = new RegExp(`${HOST_START}(?:[^\\s/@]{1,64}@)?${HOST}(?=$|[\\s/?#:,.;!)\\]>"'])`, 'iu');
158
+ function hostInText(input) {
159
+ // cut before anything runs on it: the links of visibleHtml() are cut already, a caller's own
160
+ // may not be
161
+ const text = cleanText((0, token_estimate_js_1.truncate)(input, visible_text_js_1.MAX_LINK_TEXT_LENGTH));
162
+ const userinfo = HOST_AS_USERINFO.exec(text);
163
+ if (userinfo && (0, tldts_1.parse)(userinfo[1]).isIcann) {
164
+ return userinfo[1].toLowerCase();
165
+ }
166
+ const match = HOST_IN_TEXT.exec(text);
167
+ return match ? match[1].toLowerCase() : null;
168
+ }
169
+ function urlsInText(text) {
170
+ return (String(text ?? '').match(/https?:\/\/[^\s<>"')\]]+/gi) || []).map(url => ({ href: url, text: '' }));
171
+ }
172
+ function normalizedFilename(filename) {
173
+ let name = cleanText(filename);
174
+ try {
175
+ name = decodeURIComponent(name);
176
+ }
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
+ function extensionOf(name) {
184
+ const match = /\.([a-z0-9-]+)$/i.exec(name);
185
+ return match ? match[1].toLowerCase() : '';
186
+ }
187
+ /**
188
+ * Runs the checks on a message
189
+ */
190
+ function collectSignals(message) {
191
+ const signals = [];
192
+ const seen = new Set();
193
+ const add = (code, detail) => {
194
+ const key = `${code}\n${detail}`;
195
+ if (!seen.has(key)) {
196
+ seen.add(key);
197
+ signals.push({ code, detail, floor: FLOORS[code] || 0 });
198
+ }
199
+ };
200
+ for (const attachment of [].concat(message.attachments || [])) {
201
+ const filename = normalizedFilename(attachment && attachment.filename);
202
+ const extension = extensionOf(filename);
203
+ const contentType = cleanText(attachment && attachment.contentType).toLowerCase();
204
+ if (EXECUTABLE_EXTENSIONS.has(extension) || EXECUTABLE_TYPES.has(contentType)) {
205
+ add('executableAttachment', quoted(filename || contentType));
206
+ }
207
+ else if (SCRIPTABLE_EXTENSIONS.has(extension)) {
208
+ add('scriptableAttachment', quoted(filename));
209
+ }
210
+ }
211
+ const from = splitAddress(message.from);
212
+ const fromDomain = addressDomain(from.address);
213
+ const replyTo = splitAddress(message.replyTo);
214
+ const replyToDomain = addressDomain(replyTo.address);
215
+ if (fromDomain && replyToDomain && fromDomain !== replyToDomain) {
216
+ add('replyToMismatch', `from ${quoted(fromDomain)}, replies go to ${quoted(replyToDomain)}`);
217
+ }
218
+ const nameDomain = addressDomain(from.name);
219
+ if (nameDomain && fromDomain && nameDomain !== fromDomain) {
220
+ add('displayNameAddressMismatch', `the display name reads as an address at ${quoted(nameDomain)}, the sender is at ${quoted(fromDomain)}`);
221
+ }
222
+ const links = Array.isArray(message.links) ? message.links : urlsInText(message.text);
223
+ const checked = new Set();
224
+ for (const link of links) {
225
+ const host = linkHost(link.href);
226
+ const shown = hostInText(link.text);
227
+ const key = `${host}\n${shown}`;
228
+ if (!host || checked.has(key)) {
229
+ continue;
230
+ }
231
+ checked.add(key);
232
+ if (isLookalikeHost(host)) {
233
+ add('lookalikeDomain', quoted(host));
234
+ }
235
+ if (shown && registrableDomain(shown) !== registrableDomain(host)) {
236
+ add('linkTargetMismatch', `link text says ${quoted(shown)}, the target is ${quoted(host)}`);
237
+ }
238
+ }
239
+ if ((0, authentication_js_1.authenticationFailed)(message.authentication)) {
240
+ const auth = message.authentication;
241
+ add('authenticationFailed', ['spf', 'dkim', 'dmarc'].map(method => `${method}=${auth[method] || 'none'}`).join(' '));
242
+ }
243
+ if ((message.hiddenElements ?? 0) > 0) {
244
+ add('hiddenContent', `${message.hiddenElements} hidden element(s) with text were left out`);
245
+ }
246
+ if ((message.invisibleCharacters ?? 0) > 0) {
247
+ add('invisibleCharacters', `${message.invisibleCharacters} invisible character(s) were left out`);
248
+ }
249
+ return signals;
250
+ }
251
+ /**
252
+ * The signals the model gets to see: the ones that carry a floor, without it
253
+ *
254
+ * @param signals - As returned by collectSignals()
255
+ */
256
+ function modelSignals(signals) {
257
+ return signals
258
+ .filter(signal => signal.floor > 0)
259
+ .slice(0, MAX_LISTED_SIGNALS)
260
+ .map(({ code, detail }) => ({ code, detail }));
261
+ }
262
+ /**
263
+ * Applies the signals to the model's answer: the risk score cannot be below their floor, and
264
+ * the codes of the ones that carry one are listed with the assessment so a consumer sees what
265
+ * was found. The list is always what the code found, an empty one when nothing did: the model
266
+ * writes the rest of the assessment, and text in the message can talk it into writing this
267
+ * field too, as facts no check established
268
+ *
269
+ * @param result - Normalized model output, changed in place
270
+ * @param signals - As returned by collectSignals()
271
+ * @returns The same result
272
+ */
273
+ function applySignals(result, signals) {
274
+ const scored = signals.filter(signal => signal.floor > 0);
275
+ const hasAssessment = !!result.riskAssessment && typeof result.riskAssessment === 'object';
276
+ if (!scored.length && !hasAssessment) {
277
+ return result;
278
+ }
279
+ const riskAssessment = hasAssessment ? result.riskAssessment : {};
280
+ const risk = Number.isFinite(riskAssessment.risk) ? riskAssessment.risk : 0;
281
+ const floor = scored.length ? Math.max(...scored.map(signal => signal.floor)) : 0;
282
+ if (floor > risk) {
283
+ const raised = scored
284
+ .filter(signal => signal.floor > risk)
285
+ .slice(0, MAX_LISTED_SIGNALS)
286
+ .map(signal => `${signal.code}: ${signal.detail}`);
287
+ riskAssessment.risk = floor;
288
+ riskAssessment.assessment = [riskAssessment.assessment, `Checks run on the message found: ${raised.join('; ')}.`].filter(Boolean).join(' ');
289
+ }
290
+ riskAssessment.signals = scored.slice(0, MAX_LISTED_SIGNALS).map(signal => signal.code);
291
+ result.riskAssessment = riskAssessment;
292
+ return result;
293
+ }
@@ -0,0 +1,46 @@
1
+ declare const DEFAULT_MAX_ALLOWED_TOKENS = 30000;
2
+ /**
3
+ * Estimates how many tokens a string takes
4
+ *
5
+ * @returns Estimated token count
6
+ */
7
+ declare function estimateTokens(input?: string | null): number;
8
+ /**
9
+ * Returns the length of the longest prefix of `str` that fits into `maxTokens` by the same
10
+ * estimate as estimateTokens(). Never ends between the two halves of a surrogate pair.
11
+ *
12
+ * @returns Prefix length in UTF-16 code units
13
+ */
14
+ declare function fitLength(input: string | null | undefined, maxTokens: number): number;
15
+ /**
16
+ * Cuts a string to at most `maxLength` UTF-16 code units, never between the halves of a
17
+ * surrogate pair
18
+ */
19
+ declare function truncate(input: unknown, maxLength: number): string;
20
+ export interface FitPromptOptions {
21
+ /** Variable part of the prompt, the only part that gets shortened */
22
+ text?: string | null | undefined;
23
+ /** Hard cap on the text length (default MAX_ALLOWED_TEXT_LENGTH) */
24
+ maxLength?: number | undefined;
25
+ /** Token budget for the whole prompt (default DEFAULT_MAX_ALLOWED_TOKENS) */
26
+ maxTokens?: number | null | undefined;
27
+ /** The fixed parts, as strings to estimate or as token counts already estimated */
28
+ overhead?: Array<string | number> | string | number | undefined;
29
+ }
30
+ export interface PromptTooLongError extends Error {
31
+ code?: string;
32
+ originalLength?: number;
33
+ charactersRemoved?: number;
34
+ maxAllowedTokens?: number;
35
+ }
36
+ /**
37
+ * Cuts `text` so that it fits into `maxTokens` estimated tokens next to the fixed parts of the
38
+ * prompt
39
+ *
40
+ * @throws Error with code PROMPT_TOO_LONG if the fixed parts alone do not fit
41
+ */
42
+ declare function fitPrompt({ text, maxLength, maxTokens, overhead }: FitPromptOptions): {
43
+ text: string;
44
+ charactersRemoved: number;
45
+ };
46
+ export { estimateTokens, fitLength, fitPrompt, truncate, DEFAULT_MAX_ALLOWED_TOKENS };