@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.
Files changed (71) hide show
  1. package/CHANGELOG.md +19 -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 +73 -13
  46. package/.eslintrc +0 -22
  47. package/.github/VULNERABILITY_REPORT.yml +0 -75
  48. package/.github/workflows/release.yaml +0 -36
  49. package/.github/workflows/test.yaml +0 -43
  50. package/.ncurc.js +0 -18
  51. package/.prettierignore +0 -3
  52. package/.prettierrc.js +0 -10
  53. package/.release-please-manifest.json +0 -3
  54. package/CLAUDE.md +0 -150
  55. package/eslint.config.js +0 -39
  56. package/examples/fixtures/message-1.json +0 -74
  57. package/examples/list-models.js +0 -14
  58. package/examples/summary.js +0 -34
  59. package/index.js +0 -26
  60. package/release-please-config.json +0 -10
  61. package/test/api-request.test.js +0 -169
  62. package/test/authentication.test.js +0 -110
  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
package/CLAUDE.md DELETED
@@ -1,150 +0,0 @@
1
- # Claude Development Guidelines
2
-
3
- ## Project Overview
4
-
5
- `@postalsys/email-ai-tools` is a Node.js library that analyzes one parsed email
6
- at a time with an OpenAI-compatible chat model: a summary, the sentiment, whether
7
- a reply is expected, a fraud risk score, and the events and actions the message
8
- mentions. It also lists the models an endpoint serves. Version 2.0 dropped the
9
- risk-only analysis, the embeddings and the question answering over stored email,
10
- which lost their only consumer when EmailEngine removed its Document Store.
11
-
12
- It is published to npm and consumed by other Postal Systems projects - most
13
- notably EmailEngine (`../emailengine`), where it ships inside a standalone binary
14
- built with `@yao-pkg/pkg`. See **Packaging Compatibility** below; it constrains
15
- which dependencies this library may use.
16
-
17
- ## Project Structure
18
-
19
- - `index.js` - Public entry point; re-exports the functions listed below
20
- - `/lib` - Implementation modules (one feature per file)
21
- - `/test` - Tests using the Node.js native test runner (`*.test.js`)
22
- - `/test/helpers/mock-server.js` - Local mock of the OpenAI-compatible API used by tests
23
- - `/examples` - Standalone usage examples (excluded from lint and CodeQL)
24
-
25
- ### Library Modules
26
-
27
- - `lib/generate-summary.js` - `generateSummary()` plus `DEFAULT_SYSTEM_PROMPT` /
28
- `DEFAULT_INSTRUCTIONS` / `DEFAULT_MODEL`; returns `{ result, usage }`, where
29
- `result` is the model's JSON object (documented properties normalized, custom
30
- ones passed through) and `usage` the request id, model, token counts and time.
31
- The instructions and the input format description go in the system message,
32
- the email alone goes in the user message as one JSON object with decoded
33
- headers. A parameter the backend refuses with a 400 naming it
34
- (`response_format`, `reasoning_effort`, `temperature`, `top_p`) is dropped,
35
- retried and remembered per endpoint and model; reasoning models
36
- (`isReasoningModel()`) get `reasoning_effort: "low"` unless told otherwise.
37
- - `lib/visible-text.js` - drops hidden elements, scripts, styles and comments
38
- from HTML and invisible characters from text, so the model reads what the
39
- recipient sees.
40
- - `lib/signals.js` - checks run in code before the model sees the email
41
- (executable attachments, link text naming another host than its target,
42
- lookalike domains, display name and reply address mismatches, verified
43
- authentication failures, removed hidden content), passed to the model as
44
- `signals` and applied afterwards as a floor on `riskAssessment.risk`.
45
- - `lib/authentication.js` - parses the topmost Authentication-Results header
46
- into an `authentication` block marked verified when its authserv-id is one
47
- the caller trusts (`trustedAuthservIds`, `acceptUnnamedAuthentication`).
48
- - `lib/list-models.js` - `listModels()`; lists the chat models an endpoint
49
- serves, newest family first (`chatOnly: false` keeps the rest), each with a
50
- description and a recommended flag (`describeModel()`).
51
- - `lib/api-request.js` - shared HTTP request helper (size cap, JSON parsing, 429
52
- retry with Retry-After, error shaping) used by every API call.
53
- - `lib/token-estimate.js` - character-based token estimate and prompt fitting against
54
- a budget that covers the fixed parts of the prompt too.
55
-
56
- ## Technology Stack
57
-
58
- - **Runtime**: Node.js (CI tests on 22 and 24). No build step - plain CommonJS.
59
- - **Module system**: CommonJS (`'use strict';`, `require`/`module.exports`).
60
- - **HTTP**: `undici` (`fetch` + `Agent`) for all outbound API calls.
61
- - **Token budgeting**: a character-based estimate in `lib/token-estimate.js` (no
62
- tokenizer dependency); the model's own context-length error is the backstop.
63
- - **Email/text helpers**: `@postalsys/email-text-tools` (HTML to text),
64
- `libmime` (decoding encoded words in header values), `htmlparser2` with
65
- `domutils` and `dom-serializer` (hidden element removal and link extraction,
66
- pinned to their last CommonJS majors) and `tldts` (registrable domains).
67
-
68
- ## Development Commands
69
-
70
- ```
71
- npm test # Run the test suite (node --test test/*.test.js)
72
- npm run lint # Lint with ESLint
73
- npm run format # Format code with Prettier
74
- npm run update # Refresh deps: remove node_modules + lockfile, ncu -u, npm install
75
- ```
76
-
77
- ## Testing
78
-
79
- - Uses the Node.js native test runner with the native `assert` module.
80
- - Tests live in `/test` and must be named `*.test.js` - the runner glob only
81
- matches that pattern, so helpers (e.g. `test/helpers/mock-server.js`) are never
82
- picked up as test files.
83
- - Tests are hermetic: they run against the in-process mock server in
84
- `test/helpers/mock-server.js` rather than calling real OpenAI endpoints. Do not
85
- add tests that require live API credentials or network access.
86
- - Run `npm test` before committing and make sure it passes.
87
-
88
- ## Packaging Compatibility (important)
89
-
90
- EmailEngine bundles this library into a single executable with `@yao-pkg/pkg`.
91
- `pkg` snapshots the CommonJS `require` graph at build time, so **every dependency
92
- must be CommonJS-compatible**. Do not introduce pure-ESM-only packages or
93
- ESM-only versions of existing packages.
94
-
95
- - New ESM-only majors are blocked in `.ncurc.js` via the `reject` list (e.g.
96
- `nanoid` moved to ESM and is pinned).
97
- - `undici` is pinned to the 7.x line; 8.x requires Node >= 22.19.
98
- - When `npm run update` proposes an upgrade, confirm the new version still
99
- publishes a CommonJS build and still loads under `require()` before accepting
100
- it. If a package goes ESM-only, add it to the `reject` list in `.ncurc.js` with
101
- a one-line comment explaining why.
102
-
103
- ## Dependency Management
104
-
105
- - Use `npm run update` to bump dependencies (it runs `ncu -u` then a clean
106
- install). Respect the `reject` list in `.ncurc.js`.
107
- - After updating, run `npm test`, `npm run lint`, and
108
- `npx prettier --check "**/*.{js,json,md}"` to confirm nothing broke.
109
- - Keep `package.json` versions exact (no `^`/`~` ranges) to match the existing
110
- convention and keep `pkg` builds reproducible.
111
-
112
- ## Versioning & Releases
113
-
114
- - Releases are automated with **release-please** (`.github/workflows/release.yaml`).
115
- Merging Conventional Commit messages to `master` opens/updates a release PR;
116
- merging that PR tags the version, updates `CHANGELOG.md`, and publishes to npm
117
- with provenance.
118
- - Commit prefixes drive the version bump: `fix:` -> patch, `feat:` -> minor,
119
- `feat!:` / `BREAKING CHANGE:` -> major.
120
-
121
- ## Code Style Rules
122
-
123
- - CommonJS only - every module starts with `'use strict';` and uses
124
- `require`/`module.exports`. No `import`/`export`.
125
- - Never use emojis in code or documentation; printable ASCII characters only.
126
- - Use a single hyphen-minus (`-`) as a dash in user-facing strings and docs.
127
- Never use double hyphens (`--`), em dashes, or en dashes.
128
- - Formatting is owned by Prettier and linting by ESLint - run both before
129
- committing; do not hand-format against them.
130
- - **Git commit messages: do not list Claude (or any AI) as a co-author or
131
- contributor.** Write commit messages in the project's own voice.
132
- - Use Conventional Commit prefixes so release-please works (`fix:`, `feat:`,
133
- `chore:`, `docs:`, `test:`, `ci:`, `refactor:`).
134
- - For commits that do not change runtime behavior (docs, comments, CI/workflow
135
- tweaks, formatting), append `[skip ci]` to the commit message to avoid
136
- triggering the GitHub Actions workflows. Exception: do not add `[skip ci]` to
137
- commits using a `fix:` or `feat:` prefix - those must run so the release action
138
- is triggered.
139
-
140
- ## Workflow After Making Changes
141
-
142
- 1. Run `npm run format` and `npm run lint`.
143
- 2. Run `npm test` and confirm it passes.
144
- 3. Review changed code for reuse, quality, and efficiency (`/simplify`), and run
145
- `/security-review` for anything touching parsing, prompts, or outbound HTTP.
146
- 4. After pushing, check the GitHub Actions runs (e.g. `gh run list --branch master`)
147
- and report their status, including the CodeQL ("code quality") results. If a
148
- run fails for an unrelated infrastructure reason (checkout reporting "account
149
- suspended", HTTP 403, other auth errors), check https://www.githubstatus.com/
150
- for an active GitHub incident before assuming the code is at fault.
package/eslint.config.js DELETED
@@ -1,39 +0,0 @@
1
- 'use strict';
2
-
3
- const { FlatCompat } = require('@eslint/eslintrc');
4
- const js = require('@eslint/js');
5
-
6
- const compat = new FlatCompat({
7
- baseDirectory: __dirname,
8
- recommendedConfig: js.configs.recommended
9
- });
10
-
11
- module.exports = [
12
- {
13
- ignores: ['node_modules/**', 'examples/**']
14
- },
15
- ...compat.extends('nodemailer', 'prettier'),
16
- {
17
- languageOptions: {
18
- ecmaVersion: 2020,
19
- sourceType: 'script',
20
- globals: {
21
- BigInt: 'readonly'
22
- }
23
- },
24
- rules: {
25
- // Disable all formatting rules (handled by Prettier)
26
- indent: 0,
27
- quotes: 0,
28
- 'linebreak-style': 0,
29
- semi: 0,
30
- 'comma-dangle': 0,
31
- 'comma-style': 0,
32
- 'arrow-body-style': 0,
33
- 'arrow-parens': 0,
34
- // Keep these disabled
35
- 'no-await-in-loop': 0,
36
- 'require-atomic-updates': 0
37
- }
38
- }
39
- ];
@@ -1,74 +0,0 @@
1
- {
2
- "id": "AAAADQAABlw",
3
- "uid": 1628,
4
- "path": "INBOX",
5
- "date": "2022-07-06T14:12:30.000Z",
6
- "flags": ["\\Seen"],
7
- "size": 4400,
8
- "subject": "Re: proovikiri",
9
- "from": {
10
- "name": "Andris Reinman",
11
- "address": "andris.reinman@gmail.com"
12
- },
13
- "replyTo": [
14
- {
15
- "name": "Andris Reinman",
16
- "address": "andris.reinman@gmail.com"
17
- }
18
- ],
19
- "sender": {
20
- "name": "Andris Reinman",
21
- "address": "andris.reinman@gmail.com"
22
- },
23
- "to": [
24
- {
25
- "name": "andris",
26
- "address": "andris@ekiri.ee"
27
- }
28
- ],
29
- "messageId": "<A768E075-1C9F-4483-A04A-943FA920BFC5@gmail.com>",
30
- "inReplyTo": "<CAPFU5tRb4fM+4d74kkb5bjGuFr7n3kFF_TNXK=67ki93CLzGFw@mail.gmail.com>",
31
- "headers": {
32
- "return-path": ["<andris.reinman@gmail.com>"],
33
- "delivered-to": ["andris@ekiri.ee"],
34
- "received": [
35
- "from mail-lj1-f179.google.com (mail-lj1-f179.google.com [209.85.208.179]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by uvn-67-33.tll01.zonevs.eu (Postfix) with ESMTPS id 44342821FF for <andris@ekiri.ee>; Wed, 6 Jul 2022 17:12:33 +0300 (EEST)",
36
- "by mail-lj1-f179.google.com with SMTP id w2so2284874ljj.7 for <andris@ekiri.ee>; Wed, 06 Jul 2022 07:12:33 -0700 (PDT)",
37
- "from smtpclient.apple (39-152-191-90.dyn.estpak.ee. [90.191.152.39]) by smtp.gmail.com with ESMTPSA id z8-20020a05651c022800b0025d37955bc7sm947119ljn.74.2022.07.06.07.12.30 for <andris@ekiri.ee> (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128); Wed, 06 Jul 2022 07:12:31 -0700 (PDT)"
38
- ],
39
- "authentication-results": [
40
- "uvn-67-33.tll01.zonevs.eu; dkim=pass reason=\"2048-bit key; insecure key\" header.d=gmail.com header.i=@gmail.com header.b=E9nmrfaB; dkim-adsp=pass; dkim-atps=neutral"
41
- ],
42
- "dkim-signature": [
43
- "v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=from:mime-version:subject:date:references:to:in-reply-to:message-id; bh=us7LzUXeWkaVy96MNsqMB7vDjhaZ9hRrGPgxXc9icYc=; b=E9nmrfaBGUMEisRJCJy674YfEQyu2oXIF/1E7AcyGAit26CPU+vfpL3XGXmMzwWKTd S+EjMUwCc4xn4wkmxYl3nxcd3EQr1XpIpp42fK4wEfaAt7Nb3Wp+uV1pBej6Slh2TgBf j7NWyea3gyh/m09OqKAijYesJYw9YGmo+6Y7lgiNFFuIeuJRUrg5htvc6eNzoSQfnIIl QiUptLnrFFfgMRsaBkIsd4ie1/1HnLoa7ngopIRVARKRrrCNRhTqkiM93BUf8nBUDjb7 QPh8PBzzGrVvA9nDLjlSsF8t0s8Nwk9f7HApzFKAra3dzv8VnFY6zQxBm26yCjnrCxbH 8dyA=="
44
- ],
45
- "x-google-dkim-signature": [
46
- "v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:from:mime-version:subject:date:references:to :in-reply-to:message-id; bh=us7LzUXeWkaVy96MNsqMB7vDjhaZ9hRrGPgxXc9icYc=; b=0hw1EbIluZO7ZAuzBIRNVqHtNAHviTJ0RXDtefUWxyfjaaTnKkmnwPum49KIf5gGu+ J7r9tw4rGvQKLjmM1runJiZFZHq7afV3MmR4wGjjvLRA62MAdIcpAT5u8ElxjHf0nhhM OO7Yf+mYwqsB6KDeZQ5JF9LCNBvpe+TQpSXMlHANyWvh5Ofp6ugH+gLEx+8QIJHIcGBi 6cXu+pPb1GsE+M3bWY7DEiYeTDy6QQfxRZSdi9vSHFb4h/R8K6Z1/heJN+RlEGmUU2M7 fQbEuCcHfObhWMe5AmLfDXIlrx+wKxVyVxpafkLSiMQnRSvqhxVSWcUKjzr20TlHT/qH ca9g=="
47
- ],
48
- "x-gm-message-state": ["AJIora/2p0hYvgtQ3eBu7h9wBVVfY6UdVx4BO6QA32p0fTru+yWtItsi GdXLS5baocCqlr3JhbHd4ORKCa46iqRbZA=="],
49
- "x-google-smtp-source": ["AGRyM1s3m/T3Exsg6pXn6DGV9dmrrt5GV7nTjah/wAyWp+fel/88cNszkKiPBCE/I3u1VEiSO1zJMw=="],
50
- "x-received": [
51
- "by 2002:a05:651c:1032:b0:25a:780b:7140 with SMTP id w18-20020a05651c103200b0025a780b7140mr23860776ljm.319.1657116752521; Wed, 06 Jul 2022 07:12:32 -0700 (PDT)"
52
- ],
53
- "from": ["Andris Reinman <andris.reinman@gmail.com>"],
54
- "content-type": ["multipart/alternative; boundary=\"Apple-Mail=_650C0B0C-FF20-4BA0-B542-9025E8199E24\""],
55
- "mime-version": ["1.0 (Mac OS X Mail 16.0 \\(3696.100.31\\))"],
56
- "subject": ["Re: proovikiri"],
57
- "date": ["Wed, 6 Jul 2022 17:12:30 +0300"],
58
- "references": ["<CAPFU5tRb4fM+4d74kkb5bjGuFr7n3kFF_TNXK=67ki93CLzGFw@mail.gmail.com>"],
59
- "to": ["andris <andris@ekiri.ee>"],
60
- "in-reply-to": ["<CAPFU5tRb4fM+4d74kkb5bjGuFr7n3kFF_TNXK=67ki93CLzGFw@mail.gmail.com>"],
61
- "message-id": ["<A768E075-1C9F-4483-A04A-943FA920BFC5@gmail.com>"],
62
- "x-mailer": ["Apple Mail (2.3696.100.31)"]
63
- },
64
- "text": {
65
- "id": "AAAADQAABlyTkaExkaEykA",
66
- "encodedSize": {
67
- "plain": 123,
68
- "html": 590
69
- },
70
- "plain": "multi pultiu 3\n\n> On 6. Jul 2022, at 16:34, Andris Reinman <andris@postalsys.com> wrote:\n> \n> See on lihtsalt proov\n\n",
71
- "html": "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=us-ascii\"></head><body style=\"word-wrap: break-word; -webkit-nbsp-mode: space; line-break: after-white-space;\" class=\"\">multi <b class=\"\">pultiu 3</b><br class=\"\"><div><br class=\"\"><blockquote type=\"cite\" class=\"\"><div class=\"\">On 6. Jul 2022, at 16:34, Andris Reinman &lt;<a href=\"mailto:andris@postalsys.com\" class=\"\">andris@postalsys.com</a>&gt; wrote:</div><br class=\"Apple-interchange-newline\"><div class=\"\"><div dir=\"ltr\" class=\"\">See on lihtsalt proov</div>\n</div></blockquote></div><br class=\"\"></body></html>",
72
- "hasMore": false
73
- }
74
- }
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- const { listModels } = require('../lib/list-models');
4
- const util = require('util');
5
-
6
- async function main() {
7
- const result = await listModels(process.env.OPENAI_API_KEY, {
8
- verbose: true
9
- });
10
-
11
- console.log(util.inspect(result, false, 22, true));
12
- }
13
-
14
- main();
@@ -1,34 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('fs').promises;
4
- const { generateSummary } = require('../lib/generate-summary');
5
- const simpleParser = require('mailparser').simpleParser;
6
- const libmime = require('libmime');
7
- const util = require('util');
8
-
9
- async function main() {
10
- const eml = await fs.readFile(process.argv[2]);
11
-
12
- const parsed = await simpleParser(eml);
13
-
14
- const { result, usage } = await generateSummary(
15
- {
16
- headers: parsed.headerLines.map(header => libmime.decodeHeader(header.line)),
17
- attachments: parsed.attachments,
18
- html: parsed.html,
19
- text: parsed.text,
20
- subject: parsed.subject,
21
- from: parsed.from && parsed.from.value && parsed.from.value[0],
22
- date: parsed.date
23
- },
24
- process.env.OPENAI_API_KEY,
25
- {
26
- gptModel: process.env.OPENAI_MODEL,
27
- verbose: true
28
- }
29
- );
30
-
31
- console.log(util.inspect({ result, usage }, false, 22, true));
32
- }
33
-
34
- main();
package/index.js DELETED
@@ -1,26 +0,0 @@
1
- 'use strict';
2
-
3
- const {
4
- generateSummary,
5
- DEFAULT_MODEL,
6
- DEFAULT_REASONING_EFFORT,
7
- DEFAULT_MAX_TOKENS,
8
- DEFAULT_SYSTEM_PROMPT,
9
- DEFAULT_INSTRUCTIONS,
10
- REASONING_EFFORTS,
11
- ALLOWED_HEADERS
12
- } = require('./lib/generate-summary');
13
- const { listModels, describeModel } = require('./lib/list-models');
14
-
15
- module.exports = {
16
- generateSummary,
17
- listModels,
18
- describeModel,
19
- DEFAULT_MODEL,
20
- DEFAULT_REASONING_EFFORT,
21
- DEFAULT_MAX_TOKENS,
22
- DEFAULT_SYSTEM_PROMPT,
23
- DEFAULT_INSTRUCTIONS,
24
- REASONING_EFFORTS,
25
- ALLOWED_HEADERS
26
- };
@@ -1,10 +0,0 @@
1
- {
2
- "packages": {
3
- ".": {
4
- "release-type": "node",
5
- "package-name": "@postalsys/email-ai-tools",
6
- "include-component-in-tag": false,
7
- "pull-request-title-pattern": "chore${scope}: release ${version} [skip-ci]"
8
- }
9
- }
10
- }
@@ -1,169 +0,0 @@
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 } = require('./helpers/mock-server');
6
- const { apiRequest, MAX_RESPONSE_SIZE, DEFAULT_TIMEOUT } = require('../lib/api-request');
7
-
8
- const HTML_502 = '<html><head><title>502 Bad Gateway</title></head><body><center><h1>502 Bad Gateway</h1></center></body></html>';
9
-
10
- // A short per-test timeout catches a regression that waits for a long Retry-After instead of failing
11
- const TIMEOUT = { timeout: 5000 };
12
-
13
- describe('apiRequest', () => {
14
- let mock;
15
- let url;
16
-
17
- before(async () => {
18
- mock = await createMockServer();
19
- url = `${mock.url}/v1/models`;
20
- });
21
-
22
- after(async () => {
23
- await mock.close();
24
- });
25
-
26
- beforeEach(() => {
27
- mock.clearRequests();
28
- });
29
-
30
- it('sends the token, user agent and JSON payload and returns the parsed body', TIMEOUT, async () => {
31
- mock.setHandler(() => modelsResponse());
32
-
33
- const { data, time } = await apiRequest(url, { apiToken: 'secret', payload: { a: 1 } });
34
-
35
- assert.ok(Array.isArray(data.data));
36
- assert.equal(typeof time, 'number');
37
- assert.equal(mock.requests.length, 1);
38
- assert.equal(mock.requests[0].method, 'POST');
39
- assert.equal(mock.requests[0].headers.authorization, 'Bearer secret');
40
- assert.equal(mock.requests[0].headers['content-type'], 'application/json');
41
- assert.ok(/^@postalsys\/email-ai-tools\//.test(mock.requests[0].headers['user-agent']));
42
- assert.deepEqual(mock.requests[0].body, { a: 1 });
43
- });
44
-
45
- it('reports an HTML 502 with its status code instead of a JSON SyntaxError', TIMEOUT, async () => {
46
- mock.setHandler(() => ({ status: 502, raw: HTML_502 }));
47
-
48
- await assert.rejects(
49
- () => apiRequest(url, { apiToken: 'token' }),
50
- err => {
51
- assert.notEqual(err.name, 'SyntaxError');
52
- assert.equal(err.message, 'Failed to run API request');
53
- assert.equal(err.statusCode, 502);
54
- assert.ok(err.responseText.includes('502 Bad Gateway'));
55
- return true;
56
- }
57
- );
58
- assert.equal(mock.requests.length, 1);
59
- });
60
-
61
- it('retries an HTML 429 after the Retry-After delay', TIMEOUT, async () => {
62
- let calls = 0;
63
- mock.setHandler(() => {
64
- calls++;
65
- if (calls === 1) {
66
- return { status: 429, raw: '<html>Too Many Requests</html>', headers: { 'retry-after-ms': '50' } };
67
- }
68
- return modelsResponse();
69
- });
70
-
71
- const { data } = await apiRequest(url, { apiToken: 'token' });
72
-
73
- assert.equal(calls, 2);
74
- assert.ok(Array.isArray(data.data));
75
- });
76
-
77
- it('fails right away when Retry-After is longer than it is willing to wait', TIMEOUT, async () => {
78
- mock.setHandler(() => ({ status: 429, raw: '<html>Too Many Requests</html>', headers: { 'Retry-After': '3600' } }));
79
-
80
- await assert.rejects(
81
- () => apiRequest(url, { apiToken: 'token' }),
82
- err => {
83
- assert.equal(err.statusCode, 429);
84
- assert.equal(err.retryAfter, 3600);
85
- return true;
86
- }
87
- );
88
- assert.equal(mock.requests.length, 1);
89
- });
90
-
91
- it('does not produce "[object Object]" for an error object without a message', TIMEOUT, async () => {
92
- mock.setHandler(() => ({ status: 400, body: { error: { type: 'invalid_request_error', code: 'bad_input' } } }));
93
-
94
- await assert.rejects(
95
- () => apiRequest(url, { apiToken: 'token' }),
96
- err => {
97
- assert.ok(!err.message.includes('[object Object]'), err.message);
98
- assert.ok(err.message.includes('invalid_request_error'));
99
- assert.equal(err.code, 'bad_input');
100
- assert.equal(err.statusCode, 400);
101
- return true;
102
- }
103
- );
104
- });
105
-
106
- it('uses a string error as the message', TIMEOUT, async () => {
107
- mock.setHandler(() => ({ status: 400, body: { error: 'Model not found' } }));
108
-
109
- await assert.rejects(
110
- () => apiRequest(url, { apiToken: 'token' }),
111
- err => {
112
- assert.equal(err.message, 'Model not found');
113
- assert.equal(err.statusCode, 400);
114
- return true;
115
- }
116
- );
117
- });
118
-
119
- it('rejects a 200 response that is not JSON with the status and a snippet', TIMEOUT, async () => {
120
- mock.setHandler(() => ({ status: 200, raw: '<html>Login required</html>' }));
121
-
122
- await assert.rejects(
123
- () => apiRequest(url, { apiToken: 'token' }),
124
- err => {
125
- assert.equal(err.code, 'InvalidResponse');
126
- assert.equal(err.statusCode, 200);
127
- assert.ok(err.responseText.includes('Login required'));
128
- return true;
129
- }
130
- );
131
- });
132
-
133
- it('rejects a 200 response with a JSON null body', TIMEOUT, async () => {
134
- mock.setHandler(() => ({ status: 200, raw: 'null' }));
135
-
136
- await assert.rejects(() => apiRequest(url, { apiToken: 'token' }), { code: 'InvalidResponse', statusCode: 200 });
137
- });
138
-
139
- it('stops reading a response larger than the size cap', TIMEOUT, async () => {
140
- const big = 'x'.repeat(MAX_RESPONSE_SIZE + 1024);
141
- mock.setHandler(() => ({ status: 200, raw: big }));
142
-
143
- await assert.rejects(
144
- () => apiRequest(url, { apiToken: 'token' }),
145
- err => {
146
- assert.equal(err.code, 'ResponseTooLarge');
147
- assert.equal(err.statusCode, 200);
148
- return true;
149
- }
150
- );
151
- });
152
-
153
- it('gives up on a backend that never answers when the caller set no deadline', TIMEOUT, async () => {
154
- mock.setHandler(() => new Promise(resolve => setTimeout(() => resolve(modelsResponse()), 2000).unref()));
155
-
156
- await assert.rejects(() => apiRequest(url, { apiToken: 'token', timeout: 100 }), { name: 'TimeoutError' });
157
- assert.ok(DEFAULT_TIMEOUT > 0 && DEFAULT_TIMEOUT <= 10 * 60 * 1000, 'the default is a few minutes');
158
- });
159
-
160
- it('stops waiting for a 429 retry when the signal is aborted', TIMEOUT, async () => {
161
- mock.setHandler(() => ({ status: 429, raw: '', headers: { 'Retry-After': '10' } }));
162
-
163
- const controller = new AbortController();
164
- setTimeout(() => controller.abort(new Error('stopped')), 100);
165
-
166
- await assert.rejects(() => apiRequest(url, { apiToken: 'token', signal: controller.signal }), { message: 'stopped' });
167
- assert.equal(mock.requests.length, 1);
168
- });
169
- });
@@ -1,110 +0,0 @@
1
- 'use strict';
2
-
3
- const { describe, it } = require('node:test');
4
- const assert = require('node:assert/strict');
5
- const { parseAuthenticationResults, isTrustedAuthservId, authenticationBlock, authenticationFailed } = require('../lib/authentication');
6
-
7
- describe('parseAuthenticationResults', () => {
8
- it('reads the authserv-id and the first result of each method', () => {
9
- const parsed = parseAuthenticationResults(
10
- 'mx.google.com; dkim=pass header.i=@example.com header.s=sel header.b=abc; spf=pass (google.com: domain of a@example.com designates 1.2.3.4 as permitted sender) smtp.mailfrom=a@example.com; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=example.com; dkim=fail header.i=@other.example'
11
- );
12
-
13
- assert.deepEqual(parsed, { authservId: 'mx.google.com', results: { dkim: 'pass', spf: 'pass', dmarc: 'pass' } });
14
- });
15
-
16
- it('reads a header with a version and comments carrying semicolons', () => {
17
- const parsed = parseAuthenticationResults('mail.example.org 1; spf=softfail (reason; with semicolon) smtp.mailfrom=x@y.example; arc=none');
18
-
19
- assert.equal(parsed.authservId, 'mail.example.org');
20
- assert.deepEqual(parsed.results, { spf: 'softfail', arc: 'none' });
21
- });
22
-
23
- it('reads the Microsoft form, which names no server', () => {
24
- const parsed = parseAuthenticationResults(
25
- 'spf=pass (sender IP is 40.107.1.2) smtp.mailfrom=example.com; dkim=pass (signature was verified) header.d=example.com;dmarc=pass action=none header.from=example.com;compauth=pass reason=100'
26
- );
27
-
28
- assert.equal(parsed.authservId, null);
29
- assert.deepEqual(parsed.results, { spf: 'pass', dkim: 'pass', dmarc: 'pass' });
30
- });
31
-
32
- it('keeps a method=result inside a comment or a quoted string from counting', () => {
33
- const parsed = parseAuthenticationResults(
34
- 'mx.google.com; spf=fail (google.com: domain of "x);dmarc=pass;("@evil.example designates) smtp.mailfrom=x; dkim=pass (a (b) ; dmarc=pass ; (c) d); dmarc=fail'
35
- );
36
-
37
- assert.deepEqual(parsed, { authservId: 'mx.google.com', results: { spf: 'fail', dkim: 'pass', dmarc: 'fail' } });
38
- });
39
-
40
- it('returns null for an empty value', () => {
41
- assert.equal(parseAuthenticationResults(''), null);
42
- assert.equal(parseAuthenticationResults(undefined), null);
43
- });
44
- });
45
-
46
- describe('isTrustedAuthservId', () => {
47
- it('matches the name itself and hosts under it, whatever the case of the id', () => {
48
- assert.equal(isTrustedAuthservId('MX.google.com', ['mx.google.com']), true);
49
- assert.equal(isTrustedAuthservId('mx.google.com.evil.example', ['mx.google.com']), false);
50
- assert.equal(isTrustedAuthservId('evilmx.google.com', ['mx.google.com']), false);
51
- assert.equal(isTrustedAuthservId('mx1.example.com', ['example.com']), true);
52
- assert.equal(isTrustedAuthservId('notexample.com', ['example.com']), false);
53
- assert.equal(isTrustedAuthservId('example.com', ['mx1.example.com']), false);
54
- assert.equal(isTrustedAuthservId('mx.google.com', []), false);
55
- });
56
-
57
- it('accepts a missing name only when told to', () => {
58
- assert.equal(isTrustedAuthservId(null, ['mx.google.com']), false);
59
- assert.equal(isTrustedAuthservId(null, ['mx.google.com'], true), true);
60
- });
61
- });
62
-
63
- describe('authenticationBlock', () => {
64
- it('marks a verdict from a trusted server as verified', () => {
65
- assert.deepEqual(
66
- authenticationBlock('mx.google.com; spf=pass; dkim=pass; dmarc=pass', {
67
- trustedAuthservIds: ['mx.google.com'],
68
- acceptUnnamedAuthentication: false
69
- }),
70
- {
71
- verified: true,
72
- authservId: 'mx.google.com',
73
- spf: 'pass',
74
- dkim: 'pass',
75
- dmarc: 'pass'
76
- }
77
- );
78
- });
79
-
80
- it('keeps an unverified verdict, marked as such', () => {
81
- const block = authenticationBlock('attacker.example; spf=pass; dkim=pass; dmarc=pass', {
82
- trustedAuthservIds: ['mx.google.com'],
83
- acceptUnnamedAuthentication: false
84
- });
85
-
86
- assert.equal(block.verified, false);
87
- assert.equal(block.authservId, 'attacker.example');
88
- assert.equal(block.dmarc, 'pass');
89
- });
90
-
91
- it('returns null without a header', () => {
92
- assert.equal(authenticationBlock('', { trustedAuthservIds: [], acceptUnnamedAuthentication: false }), null);
93
- });
94
- });
95
-
96
- describe('authenticationFailed', () => {
97
- it('is true for a verified DMARC failure, or SPF and DKIM both failing without DMARC', () => {
98
- assert.equal(authenticationFailed({ verified: true, dmarc: 'fail', spf: 'pass' }), true);
99
- assert.equal(authenticationFailed({ verified: true, spf: 'fail', dkim: 'fail' }), true);
100
- assert.equal(authenticationFailed({ verified: true, spf: 'softfail', dkim: 'permerror' }), true);
101
- });
102
-
103
- it('is false for a pass, a partial failure, an unverified verdict or no verdict', () => {
104
- assert.equal(authenticationFailed({ verified: true, spf: 'pass', dkim: 'pass', dmarc: 'pass' }), false);
105
- assert.equal(authenticationFailed({ verified: true, spf: 'fail', dkim: 'pass' }), false);
106
- assert.equal(authenticationFailed({ verified: true, spf: 'fail', dkim: 'fail', dmarc: 'pass' }), false);
107
- assert.equal(authenticationFailed({ verified: false, dmarc: 'fail' }), false);
108
- assert.equal(authenticationFailed(null), false);
109
- });
110
- });