@postalsys/email-ai-tools 2.2.7 → 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.
- package/CHANGELOG.md +19 -0
- package/README.md +1 -1
- package/dist/cjs/index.d.ts +28 -0
- package/dist/cjs/index.js +67 -0
- package/dist/cjs/lib/api-request.d.ts +42 -0
- package/dist/cjs/lib/api-request.js +183 -0
- package/dist/cjs/lib/authentication.d.ts +46 -0
- package/{lib → dist/cjs/lib}/authentication.js +33 -44
- package/dist/cjs/lib/generate-summary.d.ts +143 -0
- package/dist/cjs/lib/generate-summary.js +562 -0
- package/dist/cjs/lib/get-api-url.d.ts +19 -0
- package/dist/cjs/lib/get-api-url.js +37 -0
- package/dist/cjs/lib/list-models.d.ts +46 -0
- package/dist/cjs/lib/list-models.js +125 -0
- package/dist/cjs/lib/signals.d.ts +72 -0
- package/dist/cjs/lib/signals.js +293 -0
- package/dist/cjs/lib/token-estimate.d.ts +46 -0
- package/{lib → dist/cjs/lib}/token-estimate.js +21 -50
- package/dist/cjs/lib/visible-text.d.ts +33 -0
- package/dist/cjs/lib/visible-text.js +182 -0
- package/dist/cjs/package-info.d.ts +2 -0
- package/dist/cjs/package-info.js +6 -0
- package/dist/cjs/package.json +3 -0
- package/dist/esm/index.d.ts +28 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/lib/api-request.d.ts +42 -0
- package/{lib → dist/esm/lib}/api-request.js +20 -53
- package/dist/esm/lib/authentication.d.ts +46 -0
- package/dist/esm/lib/authentication.js +149 -0
- package/dist/esm/lib/generate-summary.d.ts +143 -0
- package/{lib → dist/esm/lib}/generate-summary.js +59 -155
- package/dist/esm/lib/get-api-url.d.ts +19 -0
- package/{lib → dist/esm/lib}/get-api-url.js +4 -13
- package/dist/esm/lib/list-models.d.ts +46 -0
- package/{lib → dist/esm/lib}/list-models.js +19 -50
- package/dist/esm/lib/signals.d.ts +72 -0
- package/{lib → dist/esm/lib}/signals.js +33 -79
- package/dist/esm/lib/token-estimate.d.ts +46 -0
- package/dist/esm/lib/token-estimate.js +108 -0
- package/dist/esm/lib/visible-text.d.ts +33 -0
- package/{lib → dist/esm/lib}/visible-text.js +14 -40
- package/dist/esm/package-info.d.ts +2 -0
- package/dist/esm/package-info.js +3 -0
- package/dist/esm/package.json +3 -0
- package/package.json +73 -13
- package/.eslintrc +0 -22
- package/.github/VULNERABILITY_REPORT.yml +0 -75
- package/.github/workflows/release.yaml +0 -36
- package/.github/workflows/test.yaml +0 -43
- package/.ncurc.js +0 -18
- package/.prettierignore +0 -3
- package/.prettierrc.js +0 -10
- package/.release-please-manifest.json +0 -3
- package/CLAUDE.md +0 -150
- package/eslint.config.js +0 -39
- package/examples/fixtures/message-1.json +0 -74
- package/examples/list-models.js +0 -14
- package/examples/summary.js +0 -34
- package/index.js +0 -26
- package/release-please-config.json +0 -10
- package/test/api-request.test.js +0 -169
- package/test/authentication.test.js +0 -110
- package/test/dispatcher.test.js +0 -94
- package/test/generate-summary.test.js +0 -795
- package/test/get-api-url.test.js +0 -52
- package/test/helpers/mock-server.js +0 -120
- package/test/index.test.js +0 -57
- package/test/list-models.test.js +0 -302
- package/test/signals.test.js +0 -264
- package/test/token-estimate.test.js +0 -164
- package/test/visible-text.test.js +0 -144
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Dispatcher } from 'undici';
|
|
2
|
+
export interface ModelDescription {
|
|
3
|
+
description: string;
|
|
4
|
+
recommended: boolean;
|
|
5
|
+
}
|
|
6
|
+
/** A model listModels() returns: the entry the API listed, with a display name and a description */
|
|
7
|
+
export interface ModelEntry extends ModelDescription {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
[key: string]: unknown;
|
|
11
|
+
}
|
|
12
|
+
export interface ListModelsOptions {
|
|
13
|
+
/** Custom API base URL (default: OpenAI API) */
|
|
14
|
+
baseApiUrl?: string | undefined;
|
|
15
|
+
/** Leave out models that are not chat models (default true) */
|
|
16
|
+
chatOnly?: boolean | undefined;
|
|
17
|
+
/** Log the request and include the request time */
|
|
18
|
+
verbose?: boolean | undefined;
|
|
19
|
+
/** undici Dispatcher the request is sent through */
|
|
20
|
+
dispatcher?: Dispatcher | undefined;
|
|
21
|
+
/** Aborts the request */
|
|
22
|
+
signal?: AbortSignal | undefined;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A short note on a model and whether it suits email triage
|
|
26
|
+
*
|
|
27
|
+
* @param input - Model name
|
|
28
|
+
* @returns An empty description for a name nothing is known about
|
|
29
|
+
*/
|
|
30
|
+
declare function describeModel(input: unknown): ModelDescription;
|
|
31
|
+
/**
|
|
32
|
+
* The pattern of model names listModels() leaves out for an endpoint
|
|
33
|
+
*
|
|
34
|
+
* @param baseApiUrl - Base API URL (default: OpenAI API)
|
|
35
|
+
*/
|
|
36
|
+
declare function nonChatModelPattern(baseApiUrl?: string | null): RegExp;
|
|
37
|
+
/**
|
|
38
|
+
* Lists the models the API endpoint serves, newest family first, with a display name for each
|
|
39
|
+
*
|
|
40
|
+
* @param apiToken - API authentication token
|
|
41
|
+
*/
|
|
42
|
+
declare function listModels(apiToken: string, opts?: ListModelsOptions | null): Promise<{
|
|
43
|
+
models: ModelEntry[];
|
|
44
|
+
_time?: number;
|
|
45
|
+
}>;
|
|
46
|
+
export { listModels, describeModel, nonChatModelPattern };
|
|
@@ -1,24 +1,15 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
const { apiRequest } = require('./api-request');
|
|
4
|
-
|
|
5
|
-
const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
|
|
6
|
-
|
|
1
|
+
import { apiRequest } from './api-request.js';
|
|
2
|
+
import { getApiUrl, OPENAI_API_BASE_URL } from './get-api-url.js';
|
|
7
3
|
const OPENAI_API_MODELS = '/v1/models';
|
|
8
4
|
const OPENAI_API_HOST = new URL(OPENAI_API_BASE_URL).hostname;
|
|
9
|
-
|
|
10
5
|
// On OpenAI's own endpoint the names are known, and these are not chat models: embeddings,
|
|
11
6
|
// speech, images, video, moderation, the legacy completion models, and the chat models that are
|
|
12
7
|
// specialised for something else
|
|
13
|
-
const OPENAI_NON_CHAT_MODEL =
|
|
14
|
-
/embedding|tts|whisper|transcribe|dall-e|image|realtime|^gpt-live|audio|moderation|babbage|davinci|sora|instruct|codex|search|computer-use|cyber|daybreak|rosalind/i;
|
|
15
|
-
|
|
8
|
+
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;
|
|
16
9
|
// Elsewhere the names are whatever the operator pulled ("Llama-3.1-8B-Instruct" is a chat model
|
|
17
10
|
// there), so only the unmistakable ones are left out
|
|
18
11
|
const GENERIC_NON_CHAT_MODEL = /embed|whisper|tts|rerank/i;
|
|
19
|
-
|
|
20
12
|
const DATED_SNAPSHOT = /-\d{4}-\d{2}-\d{2}$|-\d{4,}$/;
|
|
21
|
-
|
|
22
13
|
// What a model is good for, by family, for a picker that shows more than a name. Recommended
|
|
23
14
|
// marks the ones that suit email triage: capable enough for it and cheap enough to run on every
|
|
24
15
|
// message. Prices change, so the notes stay qualitative
|
|
@@ -38,15 +29,14 @@ const MODEL_NOTES = [
|
|
|
38
29
|
[/chat/, 'Conversational model, not a reasoning model', false],
|
|
39
30
|
[/^gpt-oss/, 'Open-weight reasoning model', false]
|
|
40
31
|
];
|
|
41
|
-
|
|
42
32
|
/**
|
|
43
33
|
* A short note on a model and whether it suits email triage
|
|
44
34
|
*
|
|
45
|
-
* @param
|
|
46
|
-
* @returns
|
|
35
|
+
* @param input - Model name
|
|
36
|
+
* @returns An empty description for a name nothing is known about
|
|
47
37
|
*/
|
|
48
|
-
function describeModel(
|
|
49
|
-
id = String(
|
|
38
|
+
function describeModel(input) {
|
|
39
|
+
const id = String(input ?? '');
|
|
50
40
|
const dated = DATED_SNAPSHOT.test(id);
|
|
51
41
|
for (const [pattern, description, recommended] of MODEL_NOTES) {
|
|
52
42
|
if (pattern.test(id)) {
|
|
@@ -55,23 +45,18 @@ function describeModel(id) {
|
|
|
55
45
|
}
|
|
56
46
|
return { description: dated ? 'Pinned snapshot' : '', recommended: false };
|
|
57
47
|
}
|
|
58
|
-
|
|
59
48
|
const collator = new Intl.Collator('en', { numeric: true });
|
|
60
|
-
|
|
49
|
+
function isOpenAiEndpoint(baseApiUrl) {
|
|
50
|
+
return new URL(baseApiUrl || OPENAI_API_BASE_URL).hostname === OPENAI_API_HOST;
|
|
51
|
+
}
|
|
61
52
|
/**
|
|
62
53
|
* The pattern of model names listModels() leaves out for an endpoint
|
|
63
54
|
*
|
|
64
|
-
* @param
|
|
65
|
-
* @returns {RegExp}
|
|
55
|
+
* @param baseApiUrl - Base API URL (default: OpenAI API)
|
|
66
56
|
*/
|
|
67
|
-
function isOpenAiEndpoint(baseApiUrl) {
|
|
68
|
-
return new URL(baseApiUrl || OPENAI_API_BASE_URL).hostname === OPENAI_API_HOST;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
57
|
function nonChatModelPattern(baseApiUrl) {
|
|
72
58
|
return isOpenAiEndpoint(baseApiUrl) ? OPENAI_NON_CHAT_MODEL : GENERIC_NON_CHAT_MODEL;
|
|
73
59
|
}
|
|
74
|
-
|
|
75
60
|
// Sort key: GPT families first, newest first, then the o-series, then everything else; within a
|
|
76
61
|
// family the plain name before dated snapshots and previews
|
|
77
62
|
function decorate(entry) {
|
|
@@ -84,11 +69,13 @@ function decorate(entry) {
|
|
|
84
69
|
preview: /preview/i.test(entry.id)
|
|
85
70
|
};
|
|
86
71
|
}
|
|
87
|
-
|
|
88
72
|
function compare(a, b) {
|
|
89
|
-
return a.group - b.group ||
|
|
73
|
+
return (a.group - b.group ||
|
|
74
|
+
b.version - a.version ||
|
|
75
|
+
Number(a.dated) - Number(b.dated) ||
|
|
76
|
+
Number(a.preview) - Number(b.preview) ||
|
|
77
|
+
collator.compare(a.entry.id, b.entry.id));
|
|
90
78
|
}
|
|
91
|
-
|
|
92
79
|
function formatName(id) {
|
|
93
80
|
return id
|
|
94
81
|
.replace(/-/g, ' ')
|
|
@@ -100,24 +87,14 @@ function formatName(id) {
|
|
|
100
87
|
.replace(/(\d{4}) (\d{2}) (\d{2})/g, (o, y, m, d) => `${y}-${m}-${d}`)
|
|
101
88
|
.replace(/^(gpt|tts)\s/gi, (o, n) => `${n.toUpperCase()}-`);
|
|
102
89
|
}
|
|
103
|
-
|
|
104
90
|
/**
|
|
105
91
|
* Lists the models the API endpoint serves, newest family first, with a display name for each
|
|
106
92
|
*
|
|
107
|
-
* @param
|
|
108
|
-
* @param {Object} [opts]
|
|
109
|
-
* @param {string} [opts.baseApiUrl] - Custom API base URL (default: OpenAI API)
|
|
110
|
-
* @param {boolean} [opts.chatOnly=true] - Leave out models that are not chat models
|
|
111
|
-
* @param {boolean} [opts.verbose] - Log the request and include the request time
|
|
112
|
-
* @param {Object} [opts.dispatcher] - undici Dispatcher the request is sent through
|
|
113
|
-
* @param {AbortSignal} [opts.signal] - Aborts the request
|
|
114
|
-
* @returns {Promise<{models: Array<{id: string, name: string, description: string, recommended: boolean}>}>}
|
|
93
|
+
* @param apiToken - API authentication token
|
|
115
94
|
*/
|
|
116
95
|
async function listModels(apiToken, opts) {
|
|
117
96
|
opts = opts || {};
|
|
118
|
-
|
|
119
97
|
const baseApiUrl = opts.baseApiUrl || OPENAI_API_BASE_URL;
|
|
120
|
-
|
|
121
98
|
const { data, time } = await apiRequest(getApiUrl(baseApiUrl, OPENAI_API_MODELS), {
|
|
122
99
|
method: 'get',
|
|
123
100
|
apiToken,
|
|
@@ -125,28 +102,20 @@ async function listModels(apiToken, opts) {
|
|
|
125
102
|
signal: opts.signal,
|
|
126
103
|
verbose: opts.verbose
|
|
127
104
|
});
|
|
128
|
-
|
|
129
105
|
const nonChat = nonChatModelPattern(baseApiUrl);
|
|
130
106
|
// the notes are about OpenAI's names; another endpoint's "mini" is whatever its operator pulled
|
|
131
107
|
const describe = isOpenAiEndpoint(baseApiUrl) ? describeModel : () => ({ description: '', recommended: false });
|
|
132
|
-
|
|
133
108
|
const response = {
|
|
134
109
|
models: []
|
|
135
110
|
.concat((data && data.data) || [])
|
|
136
|
-
.filter(
|
|
137
|
-
entry =>
|
|
138
|
-
entry && typeof entry.id === 'string' && entry.id && entry.owned_by !== 'openai-dev' && (opts.chatOnly === false || !nonChat.test(entry.id))
|
|
139
|
-
)
|
|
111
|
+
.filter((entry) => entry && typeof entry.id === 'string' && entry.id && entry.owned_by !== 'openai-dev' && (opts.chatOnly === false || !nonChat.test(entry.id)))
|
|
140
112
|
.map(decorate)
|
|
141
113
|
.sort(compare)
|
|
142
114
|
.map(({ entry }) => Object.assign(entry, { name: formatName(entry.id) }, describe(entry.id)))
|
|
143
115
|
};
|
|
144
|
-
|
|
145
116
|
if (opts.verbose) {
|
|
146
117
|
response._time = time;
|
|
147
118
|
}
|
|
148
|
-
|
|
149
119
|
return response;
|
|
150
120
|
}
|
|
151
|
-
|
|
152
|
-
module.exports = { listModels, describeModel, nonChatModelPattern };
|
|
121
|
+
export { listModels, describeModel, nonChatModelPattern };
|
|
@@ -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 };
|
|
@@ -1,16 +1,12 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const { INVISIBLE_CHARS, MAX_LINK_TEXT_LENGTH } = require('./visible-text');
|
|
7
|
-
const { truncate } = require('./token-estimate');
|
|
8
|
-
|
|
1
|
+
import { getDomain, parse as parseDomain } from 'tldts';
|
|
2
|
+
import url from 'node:url';
|
|
3
|
+
import { authenticationFailed } from './authentication.js';
|
|
4
|
+
import { INVISIBLE_CHARS, MAX_LINK_TEXT_LENGTH } from './visible-text.js';
|
|
5
|
+
import { truncate } from './token-estimate.js';
|
|
9
6
|
// Checks run in code on the message before the model sees it. Each one is a fact the email
|
|
10
7
|
// cannot argue with: a model can be talked into a low score by text inside the message, code
|
|
11
8
|
// cannot. The floor is the least risk score a message carrying the signal gets, whatever the
|
|
12
9
|
// model says. A signal with no floor is only reported to the caller
|
|
13
|
-
|
|
14
10
|
// Files that run when opened. Double extensions ("invoice.pdf.exe") end in one of these too
|
|
15
11
|
const EXECUTABLE_EXTENSIONS = new Set([
|
|
16
12
|
'exe',
|
|
@@ -52,7 +48,6 @@ const EXECUTABLE_EXTENSIONS = new Set([
|
|
|
52
48
|
'settingcontent-ms',
|
|
53
49
|
'library-ms'
|
|
54
50
|
]);
|
|
55
|
-
|
|
56
51
|
const EXECUTABLE_TYPES = new Set([
|
|
57
52
|
'application/x-msdownload',
|
|
58
53
|
'application/x-msdos-program',
|
|
@@ -61,10 +56,8 @@ const EXECUTABLE_TYPES = new Set([
|
|
|
61
56
|
'application/x-dosexec',
|
|
62
57
|
'application/x-executable'
|
|
63
58
|
]);
|
|
64
|
-
|
|
65
59
|
// Files a mail client or browser runs code from when opened
|
|
66
60
|
const SCRIPTABLE_EXTENSIONS = new Set(['html', 'htm', 'shtml', 'xhtml', 'xht', 'svg', 'one']);
|
|
67
|
-
|
|
68
61
|
const FLOORS = {
|
|
69
62
|
executableAttachment: 4,
|
|
70
63
|
lookalikeDomain: 4,
|
|
@@ -74,22 +67,17 @@ const FLOORS = {
|
|
|
74
67
|
authenticationFailed: 3,
|
|
75
68
|
replyToMismatch: 2
|
|
76
69
|
};
|
|
77
|
-
|
|
78
70
|
// A detail is attacker-written text that lands in the assessment and in front of the model, so
|
|
79
71
|
// it is cleaned of anything that could reorder or hide it, cut short and quoted
|
|
80
|
-
// eslint-disable-next-line no-control-regex
|
|
81
72
|
const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/g;
|
|
82
73
|
const DETAIL_LENGTH = 80;
|
|
83
|
-
|
|
84
74
|
// How many signals are listed, to the model and in the assessment. A message with thousands of
|
|
85
75
|
// executable attachments or mismatched links carries that many signals, each of them true, and
|
|
86
76
|
// the first few say everything the list would
|
|
87
77
|
const MAX_LISTED_SIGNALS = 20;
|
|
88
|
-
|
|
89
78
|
const LATIN = /\p{Script=Latin}/u;
|
|
90
79
|
// a letter that is not Latin: the negation of (non-letters and Latin letters)
|
|
91
80
|
const NON_LATIN_LETTER = /[^\P{L}\p{Script=Latin}]/u;
|
|
92
|
-
|
|
93
81
|
function cleanText(value) {
|
|
94
82
|
return String(value ?? '')
|
|
95
83
|
.normalize('NFKC')
|
|
@@ -98,61 +86,55 @@ function cleanText(value) {
|
|
|
98
86
|
.replace(/\s+/g, ' ')
|
|
99
87
|
.trim();
|
|
100
88
|
}
|
|
101
|
-
|
|
102
89
|
function quoted(value) {
|
|
103
90
|
const text = cleanText(value);
|
|
104
91
|
return `"${text.length > DETAIL_LENGTH ? `${text.substring(0, DETAIL_LENGTH)}...` : text}"`;
|
|
105
92
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
host = domainToASCII(String(host ?? '').toLowerCase()) || String(host ?? '').toLowerCase();
|
|
93
|
+
function registrableDomain(input) {
|
|
94
|
+
const host = url.domainToASCII(String(input ?? '').toLowerCase()) || String(input ?? '').toLowerCase();
|
|
109
95
|
return getDomain(host) || host || null;
|
|
110
96
|
}
|
|
111
|
-
|
|
112
97
|
function addressDomain(address) {
|
|
113
98
|
const match = /@([^\s>@]+)\s*>?\s*$/.exec(String(address ?? ''));
|
|
114
99
|
return match ? registrableDomain(match[1]) : null;
|
|
115
100
|
}
|
|
116
|
-
|
|
117
101
|
// "Name <address>" or a bare address, as the From and Reply-To values are formatted
|
|
118
|
-
function splitAddress(
|
|
119
|
-
value = String(
|
|
102
|
+
function splitAddress(input) {
|
|
103
|
+
const value = String(input ?? '').trim();
|
|
120
104
|
const match = /^(.*?)\s*<([^<>]+)>\s*$/.exec(value);
|
|
121
105
|
if (match) {
|
|
122
106
|
return { name: match[1].replace(/^"|"$/g, '').trim(), address: match[2].trim() };
|
|
123
107
|
}
|
|
124
108
|
return { name: '', address: value };
|
|
125
109
|
}
|
|
126
|
-
|
|
127
110
|
// A label is a lookalike when it mixes Latin letters with letters of another script: "paypal"
|
|
128
111
|
// spelled with a Cyrillic "a" reads as the brand and resolves elsewhere. A label written entirely in
|
|
129
112
|
// another script is a normal internationalised name
|
|
130
113
|
function isLookalikeHost(host) {
|
|
131
|
-
return
|
|
114
|
+
return url
|
|
115
|
+
.domainToUnicode(String(host ?? ''))
|
|
132
116
|
.split('.')
|
|
133
117
|
.some(label => LATIN.test(label) && NON_LATIN_LETTER.test(label));
|
|
134
118
|
}
|
|
135
|
-
|
|
136
119
|
// The host a browser would connect to: tabs and newlines are dropped, leading and trailing
|
|
137
120
|
// controls and spaces stripped, a scheme-relative or backslashed form resolved, the host
|
|
138
121
|
// lower-cased, percent-decoded and punycoded, all by the URL parser. Only http and https count
|
|
139
|
-
function linkHost(
|
|
140
|
-
href = String(
|
|
122
|
+
function linkHost(input) {
|
|
123
|
+
const href = String(input ?? '')
|
|
141
124
|
.replace(/[\t\n\r]/g, '')
|
|
142
|
-
// eslint-disable-next-line no-control-regex
|
|
143
125
|
.replace(/^[\u0000- ]+|[\u0000- ]+$/g, '');
|
|
144
|
-
let
|
|
126
|
+
let parsed;
|
|
145
127
|
try {
|
|
146
|
-
|
|
147
|
-
}
|
|
128
|
+
parsed = new URL(href, 'https://base.invalid/');
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
148
131
|
return null;
|
|
149
132
|
}
|
|
150
|
-
if ((
|
|
133
|
+
if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || parsed.hostname === 'base.invalid') {
|
|
151
134
|
return null;
|
|
152
135
|
}
|
|
153
|
-
return
|
|
136
|
+
return parsed.hostname;
|
|
154
137
|
}
|
|
155
|
-
|
|
156
138
|
// Anchor text that names a host or URL itself, which a reader takes as the destination.
|
|
157
139
|
// Trailing punctuation is not part of it. A host written as userinfo ("paypal.com@evil.example")
|
|
158
140
|
// is what the reader takes in first, so it counts when it is a real name; otherwise the userinfo
|
|
@@ -160,14 +142,13 @@ function linkHost(href) {
|
|
|
160
142
|
// at most 64 octets (RFC 5321), and an unbounded run that backtracks for its "@" from every
|
|
161
143
|
// opening bracket in the text is quadratic
|
|
162
144
|
const HOST_START = /(?:^|[\s(<"'[])(?:https?:\/\/)?/.source;
|
|
163
|
-
const HOST = /((?:[\p{L}\p{N}-]+\.)+\p{L}{2,})
|
|
145
|
+
const HOST = /((?:[\p{L}\p{N}-]+\.)+\p{L}{2,})/u.source;
|
|
164
146
|
const HOST_AS_USERINFO = new RegExp(`${HOST_START}${HOST}@`, 'iu');
|
|
165
147
|
const HOST_IN_TEXT = new RegExp(`${HOST_START}(?:[^\\s/@]{1,64}@)?${HOST}(?=$|[\\s/?#:,.;!)\\]>"'])`, 'iu');
|
|
166
|
-
|
|
167
|
-
function hostInText(text) {
|
|
148
|
+
function hostInText(input) {
|
|
168
149
|
// cut before anything runs on it: the links of visibleHtml() are cut already, a caller's own
|
|
169
150
|
// may not be
|
|
170
|
-
text = cleanText(truncate(
|
|
151
|
+
const text = cleanText(truncate(input, MAX_LINK_TEXT_LENGTH));
|
|
171
152
|
const userinfo = HOST_AS_USERINFO.exec(text);
|
|
172
153
|
if (userinfo && parseDomain(userinfo[1]).isIcann) {
|
|
173
154
|
return userinfo[1].toLowerCase();
|
|
@@ -175,40 +156,26 @@ function hostInText(text) {
|
|
|
175
156
|
const match = HOST_IN_TEXT.exec(text);
|
|
176
157
|
return match ? match[1].toLowerCase() : null;
|
|
177
158
|
}
|
|
178
|
-
|
|
179
159
|
function urlsInText(text) {
|
|
180
160
|
return (String(text ?? '').match(/https?:\/\/[^\s<>"')\]]+/gi) || []).map(url => ({ href: url, text: '' }));
|
|
181
161
|
}
|
|
182
|
-
|
|
183
162
|
function normalizedFilename(filename) {
|
|
184
163
|
let name = cleanText(filename);
|
|
185
164
|
try {
|
|
186
165
|
name = decodeURIComponent(name);
|
|
187
|
-
}
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
188
168
|
// not percent-encoded, which is the usual case
|
|
189
169
|
}
|
|
190
170
|
// Windows drops trailing dots and spaces when saving
|
|
191
171
|
return name.replace(/[.\s]+$/, '');
|
|
192
172
|
}
|
|
193
|
-
|
|
194
173
|
function extensionOf(name) {
|
|
195
174
|
const match = /\.([a-z0-9-]+)$/i.exec(name);
|
|
196
175
|
return match ? match[1].toLowerCase() : '';
|
|
197
176
|
}
|
|
198
|
-
|
|
199
177
|
/**
|
|
200
178
|
* Runs the checks on a message
|
|
201
|
-
*
|
|
202
|
-
* @param {Object} message
|
|
203
|
-
* @param {string} [message.from] - Sender as "Name <address>"
|
|
204
|
-
* @param {string} [message.replyTo] - Reply-To as "Name <address>"
|
|
205
|
-
* @param {Array} [message.attachments] - Attachments with filename and contentType
|
|
206
|
-
* @param {Array} [message.links] - Every link of the HTML, with href and text, from visibleHtml()
|
|
207
|
-
* @param {string} [message.text] - Text body, read for links when there is no HTML
|
|
208
|
-
* @param {Object|null} [message.authentication] - As returned by authenticationBlock()
|
|
209
|
-
* @param {number} [message.hiddenElements] - Hidden elements removed from the HTML
|
|
210
|
-
* @param {number} [message.invisibleCharacters] - Invisible characters removed
|
|
211
|
-
* @returns {Array<{code: string, detail: string, floor: number}>}
|
|
212
179
|
*/
|
|
213
180
|
function collectSignals(message) {
|
|
214
181
|
const signals = [];
|
|
@@ -220,18 +187,17 @@ function collectSignals(message) {
|
|
|
220
187
|
signals.push({ code, detail, floor: FLOORS[code] || 0 });
|
|
221
188
|
}
|
|
222
189
|
};
|
|
223
|
-
|
|
224
190
|
for (const attachment of [].concat(message.attachments || [])) {
|
|
225
191
|
const filename = normalizedFilename(attachment && attachment.filename);
|
|
226
192
|
const extension = extensionOf(filename);
|
|
227
193
|
const contentType = cleanText(attachment && attachment.contentType).toLowerCase();
|
|
228
194
|
if (EXECUTABLE_EXTENSIONS.has(extension) || EXECUTABLE_TYPES.has(contentType)) {
|
|
229
195
|
add('executableAttachment', quoted(filename || contentType));
|
|
230
|
-
}
|
|
196
|
+
}
|
|
197
|
+
else if (SCRIPTABLE_EXTENSIONS.has(extension)) {
|
|
231
198
|
add('scriptableAttachment', quoted(filename));
|
|
232
199
|
}
|
|
233
200
|
}
|
|
234
|
-
|
|
235
201
|
const from = splitAddress(message.from);
|
|
236
202
|
const fromDomain = addressDomain(from.address);
|
|
237
203
|
const replyTo = splitAddress(message.replyTo);
|
|
@@ -239,12 +205,10 @@ function collectSignals(message) {
|
|
|
239
205
|
if (fromDomain && replyToDomain && fromDomain !== replyToDomain) {
|
|
240
206
|
add('replyToMismatch', `from ${quoted(fromDomain)}, replies go to ${quoted(replyToDomain)}`);
|
|
241
207
|
}
|
|
242
|
-
|
|
243
208
|
const nameDomain = addressDomain(from.name);
|
|
244
209
|
if (nameDomain && fromDomain && nameDomain !== fromDomain) {
|
|
245
210
|
add('displayNameAddressMismatch', `the display name reads as an address at ${quoted(nameDomain)}, the sender is at ${quoted(fromDomain)}`);
|
|
246
211
|
}
|
|
247
|
-
|
|
248
212
|
const links = Array.isArray(message.links) ? message.links : urlsInText(message.text);
|
|
249
213
|
const checked = new Set();
|
|
250
214
|
for (const link of links) {
|
|
@@ -262,27 +226,22 @@ function collectSignals(message) {
|
|
|
262
226
|
add('linkTargetMismatch', `link text says ${quoted(shown)}, the target is ${quoted(host)}`);
|
|
263
227
|
}
|
|
264
228
|
}
|
|
265
|
-
|
|
266
229
|
if (authenticationFailed(message.authentication)) {
|
|
267
230
|
const auth = message.authentication;
|
|
268
231
|
add('authenticationFailed', ['spf', 'dkim', 'dmarc'].map(method => `${method}=${auth[method] || 'none'}`).join(' '));
|
|
269
232
|
}
|
|
270
|
-
|
|
271
|
-
if (message.hiddenElements > 0) {
|
|
233
|
+
if ((message.hiddenElements ?? 0) > 0) {
|
|
272
234
|
add('hiddenContent', `${message.hiddenElements} hidden element(s) with text were left out`);
|
|
273
235
|
}
|
|
274
|
-
if (message.invisibleCharacters > 0) {
|
|
236
|
+
if ((message.invisibleCharacters ?? 0) > 0) {
|
|
275
237
|
add('invisibleCharacters', `${message.invisibleCharacters} invisible character(s) were left out`);
|
|
276
238
|
}
|
|
277
|
-
|
|
278
239
|
return signals;
|
|
279
240
|
}
|
|
280
|
-
|
|
281
241
|
/**
|
|
282
242
|
* The signals the model gets to see: the ones that carry a floor, without it
|
|
283
243
|
*
|
|
284
|
-
* @param
|
|
285
|
-
* @returns {Array<{code: string, detail: string}>}
|
|
244
|
+
* @param signals - As returned by collectSignals()
|
|
286
245
|
*/
|
|
287
246
|
function modelSignals(signals) {
|
|
288
247
|
return signals
|
|
@@ -290,7 +249,6 @@ function modelSignals(signals) {
|
|
|
290
249
|
.slice(0, MAX_LISTED_SIGNALS)
|
|
291
250
|
.map(({ code, detail }) => ({ code, detail }));
|
|
292
251
|
}
|
|
293
|
-
|
|
294
252
|
/**
|
|
295
253
|
* Applies the signals to the model's answer: the risk score cannot be below their floor, and
|
|
296
254
|
* the codes of the ones that carry one are listed with the assessment so a consumer sees what
|
|
@@ -298,9 +256,9 @@ function modelSignals(signals) {
|
|
|
298
256
|
* writes the rest of the assessment, and text in the message can talk it into writing this
|
|
299
257
|
* field too, as facts no check established
|
|
300
258
|
*
|
|
301
|
-
* @param
|
|
302
|
-
* @param
|
|
303
|
-
* @returns
|
|
259
|
+
* @param result - Normalized model output, changed in place
|
|
260
|
+
* @param signals - As returned by collectSignals()
|
|
261
|
+
* @returns The same result
|
|
304
262
|
*/
|
|
305
263
|
function applySignals(result, signals) {
|
|
306
264
|
const scored = signals.filter(signal => signal.floor > 0);
|
|
@@ -308,11 +266,9 @@ function applySignals(result, signals) {
|
|
|
308
266
|
if (!scored.length && !hasAssessment) {
|
|
309
267
|
return result;
|
|
310
268
|
}
|
|
311
|
-
|
|
312
269
|
const riskAssessment = hasAssessment ? result.riskAssessment : {};
|
|
313
270
|
const risk = Number.isFinite(riskAssessment.risk) ? riskAssessment.risk : 0;
|
|
314
271
|
const floor = scored.length ? Math.max(...scored.map(signal => signal.floor)) : 0;
|
|
315
|
-
|
|
316
272
|
if (floor > risk) {
|
|
317
273
|
const raised = scored
|
|
318
274
|
.filter(signal => signal.floor > risk)
|
|
@@ -321,10 +277,8 @@ function applySignals(result, signals) {
|
|
|
321
277
|
riskAssessment.risk = floor;
|
|
322
278
|
riskAssessment.assessment = [riskAssessment.assessment, `Checks run on the message found: ${raised.join('; ')}.`].filter(Boolean).join(' ');
|
|
323
279
|
}
|
|
324
|
-
|
|
325
280
|
riskAssessment.signals = scored.slice(0, MAX_LISTED_SIGNALS).map(signal => signal.code);
|
|
326
281
|
result.riskAssessment = riskAssessment;
|
|
327
282
|
return result;
|
|
328
283
|
}
|
|
329
|
-
|
|
330
|
-
module.exports = { collectSignals, modelSignals, applySignals, isLookalikeHost, splitAddress };
|
|
284
|
+
export { collectSignals, modelSignals, applySignals, isLookalikeHost, splitAddress };
|
|
@@ -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 };
|