@postalsys/email-ai-tools 1.12.1 → 1.13.1

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.
@@ -0,0 +1,207 @@
1
+ 'use strict';
2
+
3
+ const { describe, it, before, after, beforeEach } = require('node:test');
4
+ const assert = require('node:assert/strict');
5
+ const { createMockServer, modelsResponse, errorResponse } = require('./helpers/mock-server');
6
+ const { listModels } = require('../lib/list-models');
7
+
8
+ describe('listModels', () => {
9
+ let mock;
10
+
11
+ before(async () => {
12
+ mock = await createMockServer();
13
+ });
14
+
15
+ after(async () => {
16
+ await mock.close();
17
+ });
18
+
19
+ beforeEach(() => {
20
+ mock.clearRequests();
21
+ });
22
+
23
+ it('returns list of models', async () => {
24
+ mock.setHandler(() => modelsResponse());
25
+
26
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
27
+
28
+ assert.ok(Array.isArray(result.models));
29
+ assert.ok(result.models.length > 0);
30
+ });
31
+
32
+ it('sends correct GET request to models endpoint', async () => {
33
+ mock.setHandler(() => modelsResponse());
34
+
35
+ await listModels('my-api-key', { baseApiUrl: mock.url });
36
+
37
+ const req = mock.requests[0];
38
+ assert.equal(req.method, 'GET');
39
+ assert.equal(req.url, '/v1/models');
40
+ assert.ok(req.headers.authorization.includes('Bearer my-api-key'));
41
+ });
42
+
43
+ it('filters out openai-dev models', async () => {
44
+ mock.setHandler(() =>
45
+ modelsResponse([
46
+ { id: 'gpt-4', owned_by: 'openai' },
47
+ { id: 'internal-model', owned_by: 'openai-dev' },
48
+ { id: 'gpt-3.5-turbo', owned_by: 'openai' }
49
+ ])
50
+ );
51
+
52
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
53
+
54
+ assert.equal(result.models.length, 2);
55
+ assert.ok(result.models.every(m => m.owned_by !== 'openai-dev'));
56
+ });
57
+
58
+ it('sorts GPT models first', async () => {
59
+ mock.setHandler(() =>
60
+ modelsResponse([
61
+ { id: 'text-embedding-ada-002', owned_by: 'openai' },
62
+ { id: 'dall-e-3', owned_by: 'openai' },
63
+ { id: 'gpt-4', owned_by: 'openai' },
64
+ { id: 'whisper-1', owned_by: 'openai' },
65
+ { id: 'gpt-3.5-turbo', owned_by: 'openai' }
66
+ ])
67
+ );
68
+
69
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
70
+
71
+ assert.ok(result.models[0].id.startsWith('gpt'));
72
+ assert.ok(result.models[1].id.startsWith('gpt'));
73
+ });
74
+
75
+ it('sorts models with date suffixes before those without', async () => {
76
+ mock.setHandler(() =>
77
+ modelsResponse([
78
+ { id: 'gpt-4', owned_by: 'openai' },
79
+ { id: 'gpt-4-0613', owned_by: 'openai' }
80
+ ])
81
+ );
82
+
83
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
84
+ const ids = result.models.map(m => m.id);
85
+
86
+ assert.equal(ids[0], 'gpt-4');
87
+ assert.equal(ids[1], 'gpt-4-0613');
88
+ });
89
+
90
+ it('sorts preview models after non-preview', async () => {
91
+ mock.setHandler(() =>
92
+ modelsResponse([
93
+ { id: 'gpt-4-preview', owned_by: 'openai' },
94
+ { id: 'gpt-4', owned_by: 'openai' }
95
+ ])
96
+ );
97
+
98
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
99
+ const ids = result.models.map(m => m.id);
100
+
101
+ assert.equal(ids[0], 'gpt-4');
102
+ assert.equal(ids[1], 'gpt-4-preview');
103
+ });
104
+
105
+ it('formats model names - converts kebab-case to Title Case', async () => {
106
+ mock.setHandler(() => modelsResponse([{ id: 'gpt-3.5-turbo', owned_by: 'openai' }]));
107
+
108
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
109
+
110
+ assert.ok(result.models[0].name);
111
+ assert.ok(typeof result.models[0].name === 'string');
112
+ });
113
+
114
+ it('formats GPT prefix to uppercase', async () => {
115
+ mock.setHandler(() => modelsResponse([{ id: 'gpt-4', owned_by: 'openai' }]));
116
+
117
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
118
+
119
+ assert.ok(result.models[0].name.startsWith('GPT-'));
120
+ });
121
+
122
+ it('formats TTS prefix to uppercase', async () => {
123
+ mock.setHandler(() => modelsResponse([{ id: 'tts-1', owned_by: 'openai' }]));
124
+
125
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
126
+
127
+ assert.ok(result.models[0].name.startsWith('TTS-'));
128
+ });
129
+
130
+ it('formats Dall-E name correctly', async () => {
131
+ mock.setHandler(() => modelsResponse([{ id: 'dall-e-3', owned_by: 'openai' }]));
132
+
133
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
134
+
135
+ assert.ok(result.models[0].name.includes('Dall-E'));
136
+ });
137
+
138
+ it('formats date suffixes with dashes', async () => {
139
+ mock.setHandler(() => modelsResponse([{ id: 'gpt-4-2024-01-25', owned_by: 'openai' }]));
140
+
141
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
142
+
143
+ assert.ok(result.models[0].name.includes('2024-01-25'));
144
+ });
145
+
146
+ it('formats HD abbreviation to uppercase', async () => {
147
+ mock.setHandler(() => modelsResponse([{ id: 'dall-e-3-hd', owned_by: 'openai' }]));
148
+
149
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
150
+
151
+ assert.ok(result.models[0].name.includes('HD'));
152
+ });
153
+
154
+ it('includes _time in verbose mode', async () => {
155
+ mock.setHandler(() => modelsResponse());
156
+
157
+ const result = await listModels('test-token', { baseApiUrl: mock.url, verbose: true });
158
+
159
+ assert.ok('_time' in result);
160
+ assert.equal(typeof result._time, 'number');
161
+ });
162
+
163
+ it('does not include _time by default', async () => {
164
+ mock.setHandler(() => modelsResponse());
165
+
166
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
167
+
168
+ assert.ok(!('_time' in result));
169
+ });
170
+
171
+ it('retries on 429 rate limit', { timeout: 10000 }, async () => {
172
+ let callCount = 0;
173
+ mock.setHandler(() => {
174
+ callCount++;
175
+ if (callCount === 1) {
176
+ return errorResponse(429, 'Rate limited');
177
+ }
178
+ return modelsResponse();
179
+ });
180
+
181
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
182
+
183
+ assert.ok(result.models.length > 0);
184
+ assert.equal(callCount, 2);
185
+ });
186
+
187
+ it('throws on API errors', async () => {
188
+ mock.setHandler(() => errorResponse(401, 'Invalid API key', 'invalid_api_key'));
189
+
190
+ await assert.rejects(
191
+ () => listModels('test-token', { baseApiUrl: mock.url }),
192
+ err => {
193
+ assert.equal(err.message, 'Invalid API key');
194
+ assert.equal(err.statusCode, 401);
195
+ return true;
196
+ }
197
+ );
198
+ });
199
+
200
+ it('handles empty models list', async () => {
201
+ mock.setHandler(() => modelsResponse([]));
202
+
203
+ const result = await listModels('test-token', { baseApiUrl: mock.url });
204
+
205
+ assert.deepEqual(result.models, []);
206
+ });
207
+ });
@@ -0,0 +1,211 @@
1
+ 'use strict';
2
+
3
+ const { describe, it, before, after, beforeEach } = require('node:test');
4
+ const assert = require('node:assert/strict');
5
+ const { createMockServer, chatResponse, errorResponse } = require('./helpers/mock-server');
6
+ const riskAnalysis = require('../lib/risk-analysis');
7
+
8
+ describe('riskAnalysis', () => {
9
+ let mock;
10
+
11
+ before(async () => {
12
+ mock = await createMockServer();
13
+ });
14
+
15
+ after(async () => {
16
+ await mock.close();
17
+ });
18
+
19
+ beforeEach(() => {
20
+ mock.clearRequests();
21
+ });
22
+
23
+ const simpleMessage = {
24
+ headers: [
25
+ { key: 'from', value: 'sender@example.com' },
26
+ { key: 'to', value: 'recipient@example.com' },
27
+ { key: 'subject', value: 'Test Subject' },
28
+ { key: 'authentication-results', value: 'spf=pass; dkim=pass; dmarc=pass' }
29
+ ],
30
+ text: 'Hello, this is a test email.'
31
+ };
32
+
33
+ const riskResult = { risk: 1, assessment: 'Low risk, authenticated sender.' };
34
+
35
+ it('returns risk score and assessment', async () => {
36
+ mock.setHandler(() => chatResponse(riskResult));
37
+
38
+ const result = await riskAnalysis(simpleMessage, 'test-token', { baseApiUrl: mock.url });
39
+
40
+ assert.equal(result.risk, 1);
41
+ assert.equal(result.assessment, 'Low risk, authenticated sender.');
42
+ assert.equal(result.id, 'chatcmpl-test123');
43
+ assert.equal(result.tokens, 150);
44
+ assert.equal(result.model, 'gpt-5-mini');
45
+ });
46
+
47
+ it('sends correct request payload', async () => {
48
+ mock.setHandler(() => chatResponse(riskResult));
49
+
50
+ await riskAnalysis(simpleMessage, 'my-api-key', {
51
+ baseApiUrl: mock.url,
52
+ user: 'user123',
53
+ temperature: 0.5
54
+ });
55
+
56
+ const req = mock.requests[0];
57
+ assert.equal(req.method, 'POST');
58
+ assert.equal(req.url, '/v1/chat/completions');
59
+ assert.ok(req.headers.authorization.includes('Bearer my-api-key'));
60
+ assert.equal(req.body.model, 'gpt-5-mini');
61
+ assert.equal(req.body.user, 'user123');
62
+ assert.equal(req.body.temperature, 0.5);
63
+ assert.equal(req.body.messages.length, 2);
64
+ assert.equal(req.body.messages[0].role, 'system');
65
+ assert.equal(req.body.messages[1].role, 'user');
66
+ });
67
+
68
+ it('converts risk to number', async () => {
69
+ mock.setHandler(() => chatResponse({ risk: '3', assessment: 'Medium risk.' }));
70
+
71
+ const result = await riskAnalysis(simpleMessage, 'test-token', { baseApiUrl: mock.url });
72
+
73
+ assert.equal(result.risk, 3);
74
+ assert.equal(typeof result.risk, 'number');
75
+ });
76
+
77
+ it('returns -1 for non-numeric risk', async () => {
78
+ mock.setHandler(() => chatResponse({ risk: 'high', assessment: 'Could not parse.' }));
79
+
80
+ const result = await riskAnalysis(simpleMessage, 'test-token', { baseApiUrl: mock.url });
81
+
82
+ assert.equal(result.risk, -1);
83
+ });
84
+
85
+ it('filters headers with whitelist', async () => {
86
+ mock.setHandler(() => chatResponse(riskResult));
87
+
88
+ const messageWithExtraHeaders = {
89
+ headers: [
90
+ { key: 'from', value: 'test@example.com' },
91
+ { key: 'x-mailer', value: 'Thunderbird' },
92
+ { key: 'received', value: 'from mail.example.com' }
93
+ ],
94
+ text: 'Test email'
95
+ };
96
+
97
+ await riskAnalysis(messageWithExtraHeaders, 'test-token', { baseApiUrl: mock.url });
98
+
99
+ const userContent = mock.requests[0].body.messages[1].content;
100
+ assert.ok(!userContent.includes('x-mailer'));
101
+ assert.ok(!userContent.includes('Thunderbird'));
102
+ });
103
+
104
+ it('deduplicates authentication-results header', async () => {
105
+ mock.setHandler(() => chatResponse(riskResult));
106
+
107
+ const messageWithDupAuth = {
108
+ headers: [
109
+ { key: 'from', value: 'test@example.com' },
110
+ { key: 'authentication-results', value: 'spf=pass' },
111
+ { key: 'authentication-results', value: 'spf=fail' }
112
+ ],
113
+ text: 'Test'
114
+ };
115
+
116
+ await riskAnalysis(messageWithDupAuth, 'test-token', { baseApiUrl: mock.url });
117
+
118
+ const userContent = mock.requests[0].body.messages[1].content;
119
+ assert.ok(userContent.includes('spf=pass'));
120
+ });
121
+
122
+ it('converts HTML to text when significantly longer', async () => {
123
+ mock.setHandler(() => chatResponse(riskResult));
124
+
125
+ const htmlMessage = {
126
+ headers: [{ key: 'from', value: 'test@example.com' }],
127
+ text: 'Short',
128
+ html: '<div><p>This is much longer HTML content for the risk analysis test that should be used instead of the short text because it is more than twice as long.</p></div>'
129
+ };
130
+
131
+ await riskAnalysis(htmlMessage, 'test-token', { baseApiUrl: mock.url });
132
+
133
+ const userContent = mock.requests[0].body.messages[1].content;
134
+ assert.ok(userContent.includes('This is much longer HTML content'));
135
+ });
136
+
137
+ it('uses custom prompts', async () => {
138
+ mock.setHandler(() => chatResponse(riskResult));
139
+
140
+ await riskAnalysis(simpleMessage, 'test-token', {
141
+ baseApiUrl: mock.url,
142
+ systemPrompt: 'Custom security prompt',
143
+ userPrompt: 'Custom analysis instructions:'
144
+ });
145
+
146
+ const req = mock.requests[0];
147
+ assert.equal(req.body.messages[0].content, 'Custom security prompt');
148
+ assert.ok(req.body.messages[1].content.startsWith('Custom analysis instructions:'));
149
+ });
150
+
151
+ it('always includes _text, _time, _cr in response', async () => {
152
+ mock.setHandler(() => chatResponse(riskResult));
153
+
154
+ const result = await riskAnalysis(simpleMessage, 'test-token', { baseApiUrl: mock.url });
155
+
156
+ assert.ok('_text' in result);
157
+ assert.ok('_time' in result);
158
+ assert.ok('_cr' in result);
159
+ assert.equal(typeof result._time, 'number');
160
+ });
161
+
162
+ it('retries on 429 rate limit', { timeout: 10000 }, async () => {
163
+ let callCount = 0;
164
+ mock.setHandler(() => {
165
+ callCount++;
166
+ if (callCount === 1) {
167
+ return errorResponse(429, 'Rate limit exceeded');
168
+ }
169
+ return chatResponse(riskResult);
170
+ });
171
+
172
+ const result = await riskAnalysis(simpleMessage, 'test-token', { baseApiUrl: mock.url });
173
+
174
+ assert.equal(result.risk, 1);
175
+ assert.equal(callCount, 2);
176
+ });
177
+
178
+ it('throws on API errors', async () => {
179
+ mock.setHandler(() => errorResponse(401, 'Invalid API key', 'invalid_api_key'));
180
+
181
+ await assert.rejects(
182
+ () => riskAnalysis(simpleMessage, 'test-token', { baseApiUrl: mock.url }),
183
+ err => {
184
+ assert.equal(err.message, 'Invalid API key');
185
+ assert.equal(err.code, 'invalid_api_key');
186
+ assert.equal(err.statusCode, 401);
187
+ return true;
188
+ }
189
+ );
190
+ });
191
+
192
+ it('throws on invalid JSON response', async () => {
193
+ mock.setHandler(() => chatResponse('Not a JSON response'));
194
+
195
+ await assert.rejects(
196
+ () => riskAnalysis(simpleMessage, 'test-token', { baseApiUrl: mock.url }),
197
+ err => {
198
+ assert.ok(err.message.includes('Failed to parse'));
199
+ return true;
200
+ }
201
+ );
202
+ });
203
+
204
+ it('handles empty message', async () => {
205
+ mock.setHandler(() => chatResponse(riskResult));
206
+
207
+ const result = await riskAnalysis({ headers: [], text: '' }, 'test-token', { baseApiUrl: mock.url });
208
+
209
+ assert.equal(result.risk, 1);
210
+ });
211
+ });