@postalsys/email-ai-tools 2.2.8 → 2.3.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.
- 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 +65 -12
- package/.github/VULNERABILITY_REPORT.yml +0 -75
- package/.github/workflows/release.yaml +0 -37
- package/.github/workflows/test.yaml +0 -35
- package/.ncurc.js +0 -23
- package/.prettierignore +0 -5
- package/.prettierrc.js +0 -10
- package/.release-please-manifest.json +0 -3
- package/CLAUDE.md +0 -185
- package/eslint.config.js +0 -70
- 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/commonjs-graph.test.js +0 -21
- 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
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [2.3.1](https://github.com/postalsys/email-ai-tools/compare/v2.3.0...v2.3.1) (2026-10-20)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Bug Fixes
|
|
7
|
+
|
|
8
|
+
* bump tldts to 7.4.19 ([e3f7910](https://github.com/postalsys/email-ai-tools/commit/e3f791065e50b0a75840c5fd0c7335a92488f882))
|
|
9
|
+
|
|
10
|
+
## [2.3.0](https://github.com/postalsys/email-ai-tools/compare/v2.2.8...v2.3.0) (2026-10-19)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
### Features
|
|
14
|
+
|
|
15
|
+
* migrate to TypeScript with ES module and CommonJS builds ([78ab1f1](https://github.com/postalsys/email-ai-tools/commit/78ab1f1779624cd6e60616f574fd57d1eec097bf))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
### Bug Fixes
|
|
19
|
+
|
|
20
|
+
* bump email-text-tools to 2.5.0 ([c102e8e](https://github.com/postalsys/email-ai-tools/commit/c102e8e4da0b91d6b24eda1beefa3e68ddc6f329))
|
|
21
|
+
|
|
3
22
|
## [2.2.8](https://github.com/postalsys/email-ai-tools/compare/v2.2.7...v2.2.8) (2026-10-19)
|
|
4
23
|
|
|
5
24
|
|
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ Summarize and risk-score email messages with an OpenAI-compatible chat model. Th
|
|
|
8
8
|
npm install @postalsys/email-ai-tools
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
Node.js 20 or later.
|
|
11
|
+
Node.js 20 or later, no native dependencies. Ships ES module and CommonJS builds with type declarations: `import { generateSummary } from '@postalsys/email-ai-tools'` and `require('@postalsys/email-ai-tools')` both work.
|
|
12
12
|
|
|
13
13
|
## generateSummary(message, apiToken, options)
|
|
14
14
|
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import * as summary from './lib/generate-summary.js';
|
|
2
|
+
import * as models from './lib/list-models.js';
|
|
3
|
+
export type { GenerateSummaryOptions, SummaryAddress, SummaryError, SummaryMessage, SummaryResult, SummaryUsage } from './lib/generate-summary.js';
|
|
4
|
+
export type { ListModelsOptions, ModelDescription, ModelEntry } from './lib/list-models.js';
|
|
5
|
+
export type { Signal } from './lib/signals.js';
|
|
6
|
+
export declare const generateSummary: typeof summary.generateSummary;
|
|
7
|
+
export declare const listModels: typeof models.listModels;
|
|
8
|
+
export declare const describeModel: typeof models.describeModel;
|
|
9
|
+
export declare const DEFAULT_MODEL = "gpt-6-luna";
|
|
10
|
+
export declare const DEFAULT_REASONING_EFFORT = "low";
|
|
11
|
+
export declare const DEFAULT_MAX_TOKENS = 30000;
|
|
12
|
+
export declare const DEFAULT_SYSTEM_PROMPT: string;
|
|
13
|
+
export declare const DEFAULT_INSTRUCTIONS: string;
|
|
14
|
+
export declare const REASONING_EFFORTS: string[];
|
|
15
|
+
export declare const ALLOWED_HEADERS: readonly string[];
|
|
16
|
+
declare const emailAiTools: {
|
|
17
|
+
generateSummary: typeof summary.generateSummary;
|
|
18
|
+
listModels: typeof models.listModels;
|
|
19
|
+
describeModel: typeof models.describeModel;
|
|
20
|
+
DEFAULT_MODEL: string;
|
|
21
|
+
DEFAULT_REASONING_EFFORT: string;
|
|
22
|
+
DEFAULT_MAX_TOKENS: number;
|
|
23
|
+
DEFAULT_SYSTEM_PROMPT: string;
|
|
24
|
+
DEFAULT_INSTRUCTIONS: string;
|
|
25
|
+
REASONING_EFFORTS: string[];
|
|
26
|
+
ALLOWED_HEADERS: readonly string[];
|
|
27
|
+
};
|
|
28
|
+
export default emailAiTools;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// The public entry point. Every member is declared here as its own constant rather than
|
|
3
|
+
// re-exported (`export { x } from`), because the CommonJS output of a re-export is a getter and
|
|
4
|
+
// `require('@postalsys/email-ai-tools')` has always returned plain writable properties.
|
|
5
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
6
|
+
if (k2 === undefined) k2 = k;
|
|
7
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
8
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
9
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
10
|
+
}
|
|
11
|
+
Object.defineProperty(o, k2, desc);
|
|
12
|
+
}) : (function(o, m, k, k2) {
|
|
13
|
+
if (k2 === undefined) k2 = k;
|
|
14
|
+
o[k2] = m[k];
|
|
15
|
+
}));
|
|
16
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
17
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
18
|
+
}) : function(o, v) {
|
|
19
|
+
o["default"] = v;
|
|
20
|
+
});
|
|
21
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
22
|
+
var ownKeys = function(o) {
|
|
23
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
24
|
+
var ar = [];
|
|
25
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
26
|
+
return ar;
|
|
27
|
+
};
|
|
28
|
+
return ownKeys(o);
|
|
29
|
+
};
|
|
30
|
+
return function (mod) {
|
|
31
|
+
if (mod && mod.__esModule) return mod;
|
|
32
|
+
var result = {};
|
|
33
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
34
|
+
__setModuleDefault(result, mod);
|
|
35
|
+
return result;
|
|
36
|
+
};
|
|
37
|
+
})();
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.ALLOWED_HEADERS = exports.REASONING_EFFORTS = exports.DEFAULT_INSTRUCTIONS = exports.DEFAULT_SYSTEM_PROMPT = exports.DEFAULT_MAX_TOKENS = exports.DEFAULT_REASONING_EFFORT = exports.DEFAULT_MODEL = exports.describeModel = exports.listModels = exports.generateSummary = void 0;
|
|
40
|
+
const summary = __importStar(require("./lib/generate-summary.js"));
|
|
41
|
+
const models = __importStar(require("./lib/list-models.js"));
|
|
42
|
+
exports.generateSummary = summary.generateSummary;
|
|
43
|
+
exports.listModels = models.listModels;
|
|
44
|
+
exports.describeModel = models.describeModel;
|
|
45
|
+
exports.DEFAULT_MODEL = summary.DEFAULT_MODEL;
|
|
46
|
+
exports.DEFAULT_REASONING_EFFORT = summary.DEFAULT_REASONING_EFFORT;
|
|
47
|
+
exports.DEFAULT_MAX_TOKENS = summary.DEFAULT_MAX_TOKENS;
|
|
48
|
+
exports.DEFAULT_SYSTEM_PROMPT = summary.DEFAULT_SYSTEM_PROMPT;
|
|
49
|
+
exports.DEFAULT_INSTRUCTIONS = summary.DEFAULT_INSTRUCTIONS;
|
|
50
|
+
exports.REASONING_EFFORTS = summary.REASONING_EFFORTS;
|
|
51
|
+
exports.ALLOWED_HEADERS = summary.ALLOWED_HEADERS;
|
|
52
|
+
// For `import emailAiTools from '@postalsys/email-ai-tools'`. In the CommonJS build the default
|
|
53
|
+
// export is replaced by the exports object itself, non-enumerable (scripts/build.js)
|
|
54
|
+
const emailAiTools = {
|
|
55
|
+
generateSummary: exports.generateSummary,
|
|
56
|
+
listModels: exports.listModels,
|
|
57
|
+
describeModel: exports.describeModel,
|
|
58
|
+
DEFAULT_MODEL: exports.DEFAULT_MODEL,
|
|
59
|
+
DEFAULT_REASONING_EFFORT: exports.DEFAULT_REASONING_EFFORT,
|
|
60
|
+
DEFAULT_MAX_TOKENS: exports.DEFAULT_MAX_TOKENS,
|
|
61
|
+
DEFAULT_SYSTEM_PROMPT: exports.DEFAULT_SYSTEM_PROMPT,
|
|
62
|
+
DEFAULT_INSTRUCTIONS: exports.DEFAULT_INSTRUCTIONS,
|
|
63
|
+
REASONING_EFFORTS: exports.REASONING_EFFORTS,
|
|
64
|
+
ALLOWED_HEADERS: exports.ALLOWED_HEADERS
|
|
65
|
+
};
|
|
66
|
+
exports.default = emailAiTools;
|
|
67
|
+
Object.defineProperty(exports, 'default', { value: exports, enumerable: false, writable: true, configurable: true });
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Dispatcher } from 'undici';
|
|
2
|
+
/** An error from apiRequest(), with what the API said about it */
|
|
3
|
+
export interface ApiRequestError extends Error {
|
|
4
|
+
code?: string;
|
|
5
|
+
statusCode?: number;
|
|
6
|
+
/** Which request parameter a 400 is about, when the API says */
|
|
7
|
+
param?: string;
|
|
8
|
+
type?: string;
|
|
9
|
+
/** Seconds the API asked to wait, from a 429 */
|
|
10
|
+
retryAfter?: number;
|
|
11
|
+
/** The start of a response that was not JSON */
|
|
12
|
+
responseText?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ApiRequestOptions {
|
|
15
|
+
/** Default 'post' */
|
|
16
|
+
method?: string | undefined;
|
|
17
|
+
/** Sent as a Bearer token */
|
|
18
|
+
apiToken: string;
|
|
19
|
+
/** JSON request body */
|
|
20
|
+
payload?: unknown;
|
|
21
|
+
/** undici Dispatcher, the module's own agent when omitted */
|
|
22
|
+
dispatcher?: Dispatcher | undefined;
|
|
23
|
+
/** Aborts the request and any retry wait; without one the call is given `timeout` in all */
|
|
24
|
+
signal?: AbortSignal | undefined;
|
|
25
|
+
/** Deadline in milliseconds for the whole call when no signal is given (default DEFAULT_TIMEOUT) */
|
|
26
|
+
timeout?: number | undefined;
|
|
27
|
+
/** Logs the request and the response to stderr */
|
|
28
|
+
verbose?: boolean | undefined;
|
|
29
|
+
}
|
|
30
|
+
declare const DEFAULT_TIMEOUT: number;
|
|
31
|
+
declare const MAX_RESPONSE_SIZE: number;
|
|
32
|
+
/**
|
|
33
|
+
* Sends a request to an OpenAI-compatible API and returns the parsed JSON response body
|
|
34
|
+
*
|
|
35
|
+
* @param url - Request URL
|
|
36
|
+
* @returns Parsed response body and the time the request took in milliseconds
|
|
37
|
+
*/
|
|
38
|
+
declare function apiRequest(url: string, opts: ApiRequestOptions): Promise<{
|
|
39
|
+
data: any;
|
|
40
|
+
time: number;
|
|
41
|
+
}>;
|
|
42
|
+
export { apiRequest, MAX_RESPONSE_SIZE, DEFAULT_TIMEOUT };
|
|
@@ -0,0 +1,183 @@
|
|
|
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.DEFAULT_TIMEOUT = exports.MAX_RESPONSE_SIZE = void 0;
|
|
7
|
+
exports.apiRequest = apiRequest;
|
|
8
|
+
const undici_1 = require("undici");
|
|
9
|
+
const promises_1 = __importDefault(require("node:timers/promises"));
|
|
10
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
11
|
+
const node_util_1 = __importDefault(require("node:util"));
|
|
12
|
+
const package_info_js_1 = require("../package-info.js");
|
|
13
|
+
const fetchAgent = new undici_1.Agent({ connect: { timeout: 90 * 1000 } });
|
|
14
|
+
// How long one call may take in all, retries included, when the caller sets no deadline of its
|
|
15
|
+
// own. undici bounds each phase of a request but nothing bounds the sum, and a chat completion
|
|
16
|
+
// waits for its headers until the answer is complete
|
|
17
|
+
const DEFAULT_TIMEOUT = 5 * 60 * 1000;
|
|
18
|
+
exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
|
|
19
|
+
const MAX_RETRIES = 5;
|
|
20
|
+
const RETRY_DELAY_MS = 1000;
|
|
21
|
+
// A 429 asking for a longer pause than this fails right away instead of holding the caller
|
|
22
|
+
const MAX_RETRY_DELAY_MS = 20 * 1000;
|
|
23
|
+
// Large enough for a batch of 3072-dimension embeddings, small enough to not buffer anything
|
|
24
|
+
const MAX_RESPONSE_SIZE = 8 * 1024 * 1024;
|
|
25
|
+
exports.MAX_RESPONSE_SIZE = MAX_RESPONSE_SIZE;
|
|
26
|
+
const RESPONSE_SNIPPET_LENGTH = 512;
|
|
27
|
+
async function sleep(ms, signal) {
|
|
28
|
+
try {
|
|
29
|
+
await promises_1.default.setTimeout(ms, undefined, { signal });
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
// report the caller's own abort reason, not the generic AbortError of the timer
|
|
33
|
+
if (err.name === 'AbortError' && signal && signal.aborted) {
|
|
34
|
+
throw signal.reason;
|
|
35
|
+
}
|
|
36
|
+
throw err;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// Returns the requested delay in milliseconds, or null if the response does not name one
|
|
40
|
+
function getRetryAfter(headers) {
|
|
41
|
+
// Azure OpenAI sends the millisecond variant
|
|
42
|
+
const retryAfterMs = (headers.get('retry-after-ms') || '').trim();
|
|
43
|
+
if (/^\d+(\.\d+)?$/.test(retryAfterMs)) {
|
|
44
|
+
return Number(retryAfterMs);
|
|
45
|
+
}
|
|
46
|
+
const retryAfter = (headers.get('retry-after') || '').trim();
|
|
47
|
+
if (!retryAfter) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
if (/^\d+(\.\d+)?$/.test(retryAfter)) {
|
|
51
|
+
return Number(retryAfter) * 1000;
|
|
52
|
+
}
|
|
53
|
+
const date = Date.parse(retryAfter);
|
|
54
|
+
if (!isNaN(date)) {
|
|
55
|
+
return Math.max(date - Date.now(), 0);
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
async function readBody(res, maxSize) {
|
|
60
|
+
const declared = Number(res.headers.get('content-length'));
|
|
61
|
+
if (declared > maxSize) {
|
|
62
|
+
await res.body?.cancel().catch(() => false);
|
|
63
|
+
throw responseTooLarge(res, maxSize);
|
|
64
|
+
}
|
|
65
|
+
const chunks = [];
|
|
66
|
+
let size = 0;
|
|
67
|
+
if (res.body) {
|
|
68
|
+
for await (const chunk of res.body) {
|
|
69
|
+
size += chunk.length;
|
|
70
|
+
if (size > maxSize) {
|
|
71
|
+
// leaving the loop cancels the stream
|
|
72
|
+
throw responseTooLarge(res, maxSize);
|
|
73
|
+
}
|
|
74
|
+
chunks.push(chunk);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return Buffer.concat(chunks).toString('utf-8');
|
|
78
|
+
}
|
|
79
|
+
function responseTooLarge(res, maxSize) {
|
|
80
|
+
const error = new Error(`API response exceeds the maximum allowed size of ${maxSize} bytes`);
|
|
81
|
+
error.code = 'ResponseTooLarge';
|
|
82
|
+
error.statusCode = res.status;
|
|
83
|
+
return error;
|
|
84
|
+
}
|
|
85
|
+
function errorMessage(apiError) {
|
|
86
|
+
if (typeof apiError === 'string') {
|
|
87
|
+
return apiError;
|
|
88
|
+
}
|
|
89
|
+
if (apiError && typeof apiError.message === 'string' && apiError.message) {
|
|
90
|
+
return apiError.message;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
return JSON.stringify(apiError);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return 'Failed to run API request';
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Sends a request to an OpenAI-compatible API and returns the parsed JSON response body
|
|
101
|
+
*
|
|
102
|
+
* @param url - Request URL
|
|
103
|
+
* @returns Parsed response body and the time the request took in milliseconds
|
|
104
|
+
*/
|
|
105
|
+
async function apiRequest(url, opts) {
|
|
106
|
+
const { method, apiToken, payload, dispatcher, verbose } = opts;
|
|
107
|
+
const signal = opts.signal || AbortSignal.timeout(opts.timeout || DEFAULT_TIMEOUT);
|
|
108
|
+
const headers = {
|
|
109
|
+
'User-Agent': `${package_info_js_1.name}/${package_info_js_1.version}`,
|
|
110
|
+
Authorization: `Bearer ${apiToken}`,
|
|
111
|
+
'Content-Type': 'application/json'
|
|
112
|
+
};
|
|
113
|
+
const requestId = node_crypto_1.default.randomBytes(8).toString('base64');
|
|
114
|
+
if (verbose) {
|
|
115
|
+
console.error(node_util_1.default.inspect({ requestId, apiUrl: url, payload }, false, 8, true));
|
|
116
|
+
}
|
|
117
|
+
const startTime = Date.now();
|
|
118
|
+
for (let attempt = 1;; attempt++) {
|
|
119
|
+
const res = await (0, undici_1.fetch)(url, {
|
|
120
|
+
method: method || 'post',
|
|
121
|
+
headers,
|
|
122
|
+
body: payload ? JSON.stringify(payload) : null,
|
|
123
|
+
dispatcher: dispatcher || fetchAgent,
|
|
124
|
+
signal
|
|
125
|
+
});
|
|
126
|
+
const text = await readBody(res, MAX_RESPONSE_SIZE);
|
|
127
|
+
let data = null;
|
|
128
|
+
try {
|
|
129
|
+
data = JSON.parse(text);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
// handled below, an HTML error page from a proxy is the usual case
|
|
133
|
+
}
|
|
134
|
+
if (!res.ok) {
|
|
135
|
+
const retryAfter = res.status === 429 ? getRetryAfter(res.headers) : null;
|
|
136
|
+
if (res.status === 429 && attempt < MAX_RETRIES) {
|
|
137
|
+
const wait = retryAfter !== null ? retryAfter : RETRY_DELAY_MS * 2 ** (attempt - 1);
|
|
138
|
+
if (wait <= MAX_RETRY_DELAY_MS) {
|
|
139
|
+
await sleep(wait, signal);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
let error;
|
|
144
|
+
if (data && data.error) {
|
|
145
|
+
error = new Error(errorMessage(data.error));
|
|
146
|
+
if (data.error.code) {
|
|
147
|
+
error.code = data.error.code;
|
|
148
|
+
}
|
|
149
|
+
// which request parameter a 400 is about, when the API says
|
|
150
|
+
if (typeof data.error.param === 'string' && data.error.param) {
|
|
151
|
+
error.param = data.error.param;
|
|
152
|
+
}
|
|
153
|
+
if (typeof data.error.type === 'string' && data.error.type) {
|
|
154
|
+
error.type = data.error.type;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
error = new Error('Failed to run API request');
|
|
159
|
+
}
|
|
160
|
+
error.statusCode = res.status;
|
|
161
|
+
if (retryAfter !== null) {
|
|
162
|
+
error.retryAfter = Math.ceil(retryAfter / 1000);
|
|
163
|
+
}
|
|
164
|
+
if (!data && text) {
|
|
165
|
+
error.responseText = text.substring(0, RESPONSE_SNIPPET_LENGTH);
|
|
166
|
+
}
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
if (!data) {
|
|
170
|
+
// not JSON at all, or a JSON null
|
|
171
|
+
const error = new Error('Invalid JSON in API response');
|
|
172
|
+
error.code = 'InvalidResponse';
|
|
173
|
+
error.statusCode = res.status;
|
|
174
|
+
error.responseText = text.substring(0, RESPONSE_SNIPPET_LENGTH);
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
const time = Date.now() - startTime;
|
|
178
|
+
if (verbose) {
|
|
179
|
+
console.error(node_util_1.default.inspect({ requestId, output: data }, false, 8, true));
|
|
180
|
+
}
|
|
181
|
+
return { data, time };
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** The parsed results, the first one per method */
|
|
2
|
+
export type AuthenticationResults = Partial<Record<'spf' | 'dkim' | 'dmarc' | 'arc', string>>;
|
|
3
|
+
/** The authentication block of the model's input */
|
|
4
|
+
export interface AuthenticationBlock extends AuthenticationResults {
|
|
5
|
+
verified: boolean;
|
|
6
|
+
authservId?: string | undefined;
|
|
7
|
+
}
|
|
8
|
+
/** Which authserv-ids count as the receiving server */
|
|
9
|
+
export interface AuthenticationTrust {
|
|
10
|
+
/** Lower-case names */
|
|
11
|
+
trustedAuthservIds: string[];
|
|
12
|
+
acceptUnnamedAuthentication: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Parses one Authentication-Results header value
|
|
16
|
+
*
|
|
17
|
+
* @param value - Header value, unfolded
|
|
18
|
+
* @returns The authserv-id (null when the header carries none, as Microsoft's do) and the first result per method
|
|
19
|
+
*/
|
|
20
|
+
declare function parseAuthenticationResults(value: unknown): {
|
|
21
|
+
authservId: string | null;
|
|
22
|
+
results: AuthenticationResults;
|
|
23
|
+
} | null;
|
|
24
|
+
/**
|
|
25
|
+
* Tells whether an authserv-id names a server the caller trusts: the name itself or a host
|
|
26
|
+
* under it
|
|
27
|
+
*
|
|
28
|
+
* @param trusted - Trusted names, lower case
|
|
29
|
+
* @param acceptUnnamed - Whether a header without an authserv-id counts, for providers that write none
|
|
30
|
+
*/
|
|
31
|
+
declare function isTrustedAuthservId(authservId: string | null | undefined, trusted: string[] | string | null | undefined, acceptUnnamed?: boolean): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* The authentication block of the model's input: the receiving server's verdict, marked as
|
|
34
|
+
* verified when the server that wrote it is one the caller trusts
|
|
35
|
+
*
|
|
36
|
+
* @param value - The topmost Authentication-Results header value
|
|
37
|
+
*/
|
|
38
|
+
declare function authenticationBlock(value: unknown, trust: AuthenticationTrust): AuthenticationBlock | null;
|
|
39
|
+
/**
|
|
40
|
+
* Whether a verified verdict says the sender failed: DMARC failed outright, or both SPF and
|
|
41
|
+
* DKIM did without DMARC saying otherwise
|
|
42
|
+
*
|
|
43
|
+
* @param authentication - As returned by authenticationBlock()
|
|
44
|
+
*/
|
|
45
|
+
declare function authenticationFailed(authentication: AuthenticationBlock | null | undefined): boolean;
|
|
46
|
+
export { parseAuthenticationResults, isTrustedAuthservId, authenticationBlock, authenticationFailed };
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
"use strict";
|
|
3
2
|
// The Authentication-Results header (RFC 8601) is where the receiving server records what it
|
|
4
3
|
// verified about the sender. A sender can add one of its own, so only a header the receiving
|
|
5
4
|
// server added counts, and that is told by its authserv-id: the name of the server that wrote
|
|
6
5
|
// it. The caller says which names it trusts for the mailbox at hand
|
|
7
|
-
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.parseAuthenticationResults = parseAuthenticationResults;
|
|
8
|
+
exports.isTrustedAuthservId = isTrustedAuthservId;
|
|
9
|
+
exports.authenticationBlock = authenticationBlock;
|
|
10
|
+
exports.authenticationFailed = authenticationFailed;
|
|
8
11
|
const METHODS = ['spf', 'dkim', 'dmarc', 'arc'];
|
|
9
|
-
|
|
10
12
|
// Splits a header value on the semicolons outside comments and quoted strings, which may carry
|
|
11
13
|
// semicolons of their own and whose content a trusted server copies from the message. Comments
|
|
12
14
|
// nest, and both are dropped from the pieces, since the grammar needs neither
|
|
@@ -15,13 +17,13 @@ function splitResinfo(value) {
|
|
|
15
17
|
let current = '';
|
|
16
18
|
let depth = 0;
|
|
17
19
|
let quoted = false;
|
|
18
|
-
|
|
19
20
|
for (let i = 0; i < value.length; i++) {
|
|
20
21
|
const char = value[i];
|
|
21
22
|
if (quoted) {
|
|
22
23
|
if (char === '\\') {
|
|
23
24
|
i++;
|
|
24
|
-
}
|
|
25
|
+
}
|
|
26
|
+
else if (char === '"') {
|
|
25
27
|
quoted = false;
|
|
26
28
|
}
|
|
27
29
|
continue;
|
|
@@ -32,43 +34,46 @@ function splitResinfo(value) {
|
|
|
32
34
|
// end the comment
|
|
33
35
|
if (char === '\\') {
|
|
34
36
|
i++;
|
|
35
|
-
}
|
|
37
|
+
}
|
|
38
|
+
else if (char === '"') {
|
|
36
39
|
quoted = true;
|
|
37
|
-
}
|
|
40
|
+
}
|
|
41
|
+
else if (char === '(') {
|
|
38
42
|
depth++;
|
|
39
|
-
}
|
|
43
|
+
}
|
|
44
|
+
else if (char === ')') {
|
|
40
45
|
depth--;
|
|
41
46
|
}
|
|
42
47
|
continue;
|
|
43
48
|
}
|
|
44
49
|
if (char === '"') {
|
|
45
50
|
quoted = true;
|
|
46
|
-
}
|
|
51
|
+
}
|
|
52
|
+
else if (char === '(') {
|
|
47
53
|
depth = 1;
|
|
48
|
-
}
|
|
54
|
+
}
|
|
55
|
+
else if (char === ';') {
|
|
49
56
|
segments.push(current.trim());
|
|
50
57
|
current = '';
|
|
51
|
-
}
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
52
60
|
current += char;
|
|
53
61
|
}
|
|
54
62
|
}
|
|
55
63
|
segments.push(current.trim());
|
|
56
|
-
|
|
57
64
|
return segments.filter(Boolean);
|
|
58
65
|
}
|
|
59
|
-
|
|
60
66
|
/**
|
|
61
67
|
* Parses one Authentication-Results header value
|
|
62
68
|
*
|
|
63
|
-
* @param
|
|
64
|
-
* @returns
|
|
69
|
+
* @param value - Header value, unfolded
|
|
70
|
+
* @returns The authserv-id (null when the header carries none, as Microsoft's do) and the first result per method
|
|
65
71
|
*/
|
|
66
72
|
function parseAuthenticationResults(value) {
|
|
67
73
|
const segments = splitResinfo(String(value ?? ''));
|
|
68
74
|
if (!segments.length) {
|
|
69
75
|
return null;
|
|
70
76
|
}
|
|
71
|
-
|
|
72
77
|
let authservId = null;
|
|
73
78
|
const first = segments[0];
|
|
74
79
|
const firstToken = first.split(/\s+/)[0];
|
|
@@ -76,12 +81,12 @@ function parseAuthenticationResults(value) {
|
|
|
76
81
|
// "authserv-id" or "authserv-id version"
|
|
77
82
|
authservId = firstToken.toLowerCase();
|
|
78
83
|
segments.shift();
|
|
79
|
-
}
|
|
84
|
+
}
|
|
85
|
+
else if (!firstToken.includes('=') && /\s[a-z0-9-]+\s*=/i.test(first)) {
|
|
80
86
|
// "authserv-id method=result" in one segment, which some servers write
|
|
81
87
|
authservId = firstToken.toLowerCase();
|
|
82
88
|
segments[0] = first.substring(firstToken.length).trim();
|
|
83
89
|
}
|
|
84
|
-
|
|
85
90
|
const results = {};
|
|
86
91
|
for (const segment of segments) {
|
|
87
92
|
const match = /^([a-z0-9-]+)\s*=\s*([a-z0-9-]+)/i.exec(segment);
|
|
@@ -99,18 +104,14 @@ function parseAuthenticationResults(value) {
|
|
|
99
104
|
results[method] = result;
|
|
100
105
|
}
|
|
101
106
|
}
|
|
102
|
-
|
|
103
107
|
return { authservId, results };
|
|
104
108
|
}
|
|
105
|
-
|
|
106
109
|
/**
|
|
107
110
|
* Tells whether an authserv-id names a server the caller trusts: the name itself or a host
|
|
108
111
|
* under it
|
|
109
112
|
*
|
|
110
|
-
* @param
|
|
111
|
-
* @param
|
|
112
|
-
* @param {boolean} acceptUnnamed - Whether a header without an authserv-id counts, for providers that write none
|
|
113
|
-
* @returns {boolean}
|
|
113
|
+
* @param trusted - Trusted names, lower case
|
|
114
|
+
* @param acceptUnnamed - Whether a header without an authserv-id counts, for providers that write none
|
|
114
115
|
*/
|
|
115
116
|
function isTrustedAuthservId(authservId, trusted, acceptUnnamed) {
|
|
116
117
|
if (!authservId) {
|
|
@@ -119,37 +120,27 @@ function isTrustedAuthservId(authservId, trusted, acceptUnnamed) {
|
|
|
119
120
|
const id = authservId.toLowerCase();
|
|
120
121
|
return [].concat(trusted || []).some(name => name && (id === name || id.endsWith(`.${name}`)));
|
|
121
122
|
}
|
|
122
|
-
|
|
123
123
|
/**
|
|
124
124
|
* The authentication block of the model's input: the receiving server's verdict, marked as
|
|
125
125
|
* verified when the server that wrote it is one the caller trusts
|
|
126
126
|
*
|
|
127
|
-
* @param
|
|
128
|
-
* @param {Object} trust
|
|
129
|
-
* @param {string[]} trust.trustedAuthservIds - Lower-case names
|
|
130
|
-
* @param {boolean} trust.acceptUnnamedAuthentication
|
|
131
|
-
* @returns {Object|null}
|
|
127
|
+
* @param value - The topmost Authentication-Results header value
|
|
132
128
|
*/
|
|
133
129
|
function authenticationBlock(value, trust) {
|
|
134
130
|
const parsed = parseAuthenticationResults(value);
|
|
135
131
|
if (!parsed) {
|
|
136
132
|
return null;
|
|
137
133
|
}
|
|
138
|
-
return Object.assign(
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
},
|
|
143
|
-
parsed.results
|
|
144
|
-
);
|
|
134
|
+
return Object.assign({
|
|
135
|
+
verified: isTrustedAuthservId(parsed.authservId, trust.trustedAuthservIds, trust.acceptUnnamedAuthentication),
|
|
136
|
+
authservId: parsed.authservId || undefined
|
|
137
|
+
}, parsed.results);
|
|
145
138
|
}
|
|
146
|
-
|
|
147
139
|
/**
|
|
148
140
|
* Whether a verified verdict says the sender failed: DMARC failed outright, or both SPF and
|
|
149
141
|
* DKIM did without DMARC saying otherwise
|
|
150
142
|
*
|
|
151
|
-
* @param
|
|
152
|
-
* @returns {boolean}
|
|
143
|
+
* @param authentication - As returned by authenticationBlock()
|
|
153
144
|
*/
|
|
154
145
|
function authenticationFailed(authentication) {
|
|
155
146
|
if (!authentication || !authentication.verified) {
|
|
@@ -158,8 +149,6 @@ function authenticationFailed(authentication) {
|
|
|
158
149
|
if (authentication.dmarc === 'fail') {
|
|
159
150
|
return true;
|
|
160
151
|
}
|
|
161
|
-
const failed = result => ['fail', 'softfail', 'permerror'].includes(result);
|
|
152
|
+
const failed = (result) => ['fail', 'softfail', 'permerror'].includes(result);
|
|
162
153
|
return !authentication.dmarc && failed(authentication.spf) && failed(authentication.dkim);
|
|
163
154
|
}
|
|
164
|
-
|
|
165
|
-
module.exports = { parseAuthenticationResults, isTrustedAuthservId, authenticationBlock, authenticationFailed };
|