mailschema 0.3.0 → 0.3.2
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/README.md +10 -4
- package/bin/mailschema.js +22 -7
- package/dist/core/artifacts.js +12 -2
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.js +1 -0
- package/dist/core/message.d.ts +27 -0
- package/dist/core/message.js +262 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
[Mail Action Protocol](https://mailschema.org) 0.3 for JavaScript. It parses and checks MAP descriptions, type contracts and Registry implementation records, and computes the RFC 8785 digests that identify contracts. The same code runs the MailSchema specification's own checks. It has no Node.js-only dependencies, so it also runs in browsers and workers.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
|
-
npm install mailschema@0.3.
|
|
6
|
+
npm install mailschema@0.3.2
|
|
7
7
|
```
|
|
8
8
|
|
|
9
9
|
## Check a description against its contract
|
|
@@ -20,6 +20,8 @@ if (errors.length) throw new Error(errors.join('\n'));
|
|
|
20
20
|
|
|
21
21
|
`parseDescription` reads the bytes as MAP JSON (strict I-JSON within 64 KiB) and checks the core rules, or throws `InvalidDocument` with every reason. Obtain contracts from a catalogue you configure and pin them by digest; a message never chooses one.
|
|
22
22
|
|
|
23
|
+
The published types and their contracts are in the Registry, [`https://mailschema.org/registry/map-0.3.json`](https://mailschema.org/registry/map-0.3.json): each type's `contractHref` is its contract under `https://mailschema.org/artifacts/map-0.3/contracts/`, and its Registry page (`href`) links an example description of the type.
|
|
24
|
+
|
|
23
25
|
## API
|
|
24
26
|
|
|
25
27
|
- `parse(input, maxBytes)`, `canonicalize(value)`, `digest(value)`: MAP JSON and RFC 8785 digests.
|
|
@@ -27,6 +29,7 @@ if (errors.length) throw new Error(errors.join('\n'));
|
|
|
27
29
|
- `new Contract(value)`, `Contract.parse(input)`: a checked contract with `digest`, `operation(id)`, `detailsErrors(details)`, `inputErrors(operationId, input)` and `descriptionErrors(description)`.
|
|
28
30
|
- `contractErrors(value)`: why a value is not a contract, including schema keywords, formats and patterns every implementation can enforce alike.
|
|
29
31
|
- `implementationErrors(value)`, `parseImplementation(input)`: Registry implementation records.
|
|
32
|
+
- `extractMessage(input)`: the one MAP part of a received email, read from its original bytes. It returns `{ status: 'valid', description, bytes }`, `{ status: 'invalid', reason }` or `{ status: 'none' }`, and never throws for untrusted input.
|
|
30
33
|
- `PROFILE`, `CONTEXT`, `DESCRIPTION_MEDIA_TYPE`, `EFFECTS`, `CAPABILITY_KINDS` and the size limits.
|
|
31
34
|
|
|
32
35
|
The profile record, context and schemas are exported byte for byte: `mailschema/profile.json`, `mailschema/context.jsonld`, `mailschema/core.schema.json`, `mailschema/contract.schema.json` and `mailschema/implementation.schema.json`.
|
|
@@ -34,11 +37,14 @@ The profile record, context and schemas are exported byte for byte: `mailschema/
|
|
|
34
37
|
## Command line
|
|
35
38
|
|
|
36
39
|
```sh
|
|
37
|
-
npx mailschema@0.3.
|
|
38
|
-
npx mailschema@0.3.
|
|
39
|
-
npx mailschema@0.3.
|
|
40
|
+
npx mailschema@0.3.2 contract campaign-send-approval-0.1.json
|
|
41
|
+
npx mailschema@0.3.2 description description.json --contract campaign-send-approval-0.1.json
|
|
42
|
+
npx mailschema@0.3.2 implementation record.json
|
|
43
|
+
npx mailschema@0.3.2 message approval.eml > description.json
|
|
40
44
|
```
|
|
41
45
|
|
|
46
|
+
Each command first prints a line naming what it checked. `contract` prints `Valid type contract <id> <version>` and, on the second line, the contract's digest. `description` prints `Valid MAP 0.3 description <@id>` and, on the second line, the description's digest; with `--contract`, it first checks that the description uses that contract as it allows. `implementation` prints `Valid implementation record for <service>`. `message` reads a received email (a saved `.eml`), writes its one MAP description to standard output exactly as the MAP part carries it, and prints the `description` lines on standard error. A digest is `sha-256:` and the SHA-256 of the document's RFC 8785 canonical JSON, the value `digest()` returns; the description's digest is not the contract digest it names. An invalid file prints every reason on standard error and exits with status 1. Nothing is uploaded or changed.
|
|
47
|
+
|
|
42
48
|
Checking does not authenticate a message, establish a service's authority or perform an action. Those belong to the implementation, under the [specification](https://mailschema.org/specification/core).
|
|
43
49
|
|
|
44
50
|
Source: [mailschema/javascript](https://github.com/mailschema/javascript). License: MIT.
|
package/bin/mailschema.js
CHANGED
|
@@ -4,6 +4,8 @@ import { parseArgs } from 'node:util';
|
|
|
4
4
|
import {
|
|
5
5
|
Contract,
|
|
6
6
|
CONTRACT_MAX_BYTES,
|
|
7
|
+
digest,
|
|
8
|
+
extractMessage,
|
|
7
9
|
InvalidDocument,
|
|
8
10
|
parseDescription,
|
|
9
11
|
parseImplementation,
|
|
@@ -14,16 +16,23 @@ const help = `Mail Action Protocol 0.3 checks
|
|
|
14
16
|
mailschema contract <contract.json>
|
|
15
17
|
mailschema description <description.json> [--contract <contract.json>]
|
|
16
18
|
mailschema implementation <record.json>
|
|
19
|
+
mailschema message <message.eml>
|
|
17
20
|
|
|
18
21
|
contract checks a type contract and prints its digest. description checks a
|
|
19
|
-
description and, with --contract, that it uses that contract as it allows
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
description and, with --contract, that it uses that contract as it allows,
|
|
23
|
+
then prints the description's digest. implementation checks a Registry
|
|
24
|
+
implementation record. message finds a received email's one MAP part, writes
|
|
25
|
+
its description to standard output exactly as the part carries it, and prints
|
|
26
|
+
the description's digest on standard error. A digest is the SHA-256 of the
|
|
27
|
+
document's RFC 8785 canonical JSON. Nothing is uploaded or changed.`;
|
|
22
28
|
|
|
23
|
-
|
|
29
|
+
// A whole email, attachments included, is far larger than any MAP document.
|
|
30
|
+
const MESSAGE_MAX_BYTES = 26214400;
|
|
31
|
+
|
|
32
|
+
async function read(path, maxBytes = CONTRACT_MAX_BYTES, kind = 'a JSON file') {
|
|
24
33
|
const info = await stat(path);
|
|
25
|
-
if (!info.isFile() || info.size >
|
|
26
|
-
throw new Error(`Expected
|
|
34
|
+
if (!info.isFile() || info.size > maxBytes)
|
|
35
|
+
throw new Error(`Expected ${kind} of at most ${maxBytes} bytes.`);
|
|
27
36
|
return new Uint8Array(await readFile(path));
|
|
28
37
|
}
|
|
29
38
|
|
|
@@ -48,7 +57,13 @@ try {
|
|
|
48
57
|
const description = parseDescription(await read(path));
|
|
49
58
|
if (values.contract)
|
|
50
59
|
report(Contract.parse(await read(values.contract)).descriptionErrors(description));
|
|
51
|
-
console.log(`Valid MAP 0.3 description ${description['@id']}`);
|
|
60
|
+
console.log(`Valid MAP 0.3 description ${description['@id']}\n${digest(description)}`);
|
|
61
|
+
} else if (command === 'message') {
|
|
62
|
+
const result = extractMessage(await read(path, MESSAGE_MAX_BYTES, 'an email file'));
|
|
63
|
+
if (result.status === 'none') throw new Error('The message has no MAP 0.3 part.');
|
|
64
|
+
if (result.status === 'invalid') throw new Error(`The message's MAP part cannot be used: ${result.reason}.`);
|
|
65
|
+
process.stdout.write(result.bytes);
|
|
66
|
+
console.error(`Valid MAP 0.3 description ${result.description['@id']}\n${digest(result.description)}`);
|
|
52
67
|
} else if (command === 'implementation') {
|
|
53
68
|
const record = parseImplementation(await read(path));
|
|
54
69
|
console.log(`Valid implementation record for ${record.service}`);
|
package/dist/core/artifacts.js
CHANGED
|
@@ -26,5 +26,15 @@ export function createValidator() {
|
|
|
26
26
|
ajv.removeKeyword(keyword);
|
|
27
27
|
return ajv;
|
|
28
28
|
}
|
|
29
|
-
/**
|
|
30
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Each validation error as its JSON Pointer and message. An enum or const error names the
|
|
31
|
+
* values it allows, so the fix is in the message. @internal
|
|
32
|
+
*/
|
|
33
|
+
export const schemaErrors = (errors, prefix = '') => (errors ?? []).map((error) => `${prefix + error.instancePath || '/'}: ${schemaMessage(error)}`);
|
|
34
|
+
function schemaMessage(error) {
|
|
35
|
+
if (error.keyword === 'enum')
|
|
36
|
+
return `must be one of ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(', ')}`;
|
|
37
|
+
if (error.keyword === 'const')
|
|
38
|
+
return `must be ${JSON.stringify(error.params.allowedValue)}`;
|
|
39
|
+
return error.message;
|
|
40
|
+
}
|
package/dist/core/index.d.ts
CHANGED
|
@@ -4,4 +4,5 @@ export { sha256 } from './sha256.ts';
|
|
|
4
4
|
export { descriptionErrors, parseDescription, type Description } from './description.ts';
|
|
5
5
|
export { CAPABILITY_KINDS, Contract, contractErrors, type CapabilityKind, type ContractDocument, type Operation, } from './contract.ts';
|
|
6
6
|
export { implementationErrors, parseImplementation, type ImplementationRecord, } from './implementation.ts';
|
|
7
|
+
export { extractMessage, type MessageProblem, type MessageResult } from './message.ts';
|
|
7
8
|
export { unportablePattern } from './patterns.ts';
|
package/dist/core/index.js
CHANGED
|
@@ -6,4 +6,5 @@ export { sha256 } from "./sha256.js";
|
|
|
6
6
|
export { descriptionErrors, parseDescription } from "./description.js";
|
|
7
7
|
export { CAPABILITY_KINDS, Contract, contractErrors, } from "./contract.js";
|
|
8
8
|
export { implementationErrors, parseImplementation, } from "./implementation.js";
|
|
9
|
+
export { extractMessage } from "./message.js";
|
|
9
10
|
export { unportablePattern } from "./patterns.js";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type Description } from './description.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Why a message's MAP part cannot be used: more than one designated part, a header that
|
|
4
|
+
* readers could read differently, a transfer encoding other than base64 or quoted-printable,
|
|
5
|
+
* a part not labelled exactly with this profile, a part outside a multipart/related entity
|
|
6
|
+
* whose root is readable, an invalid description, or a message that cannot be read.
|
|
7
|
+
*/
|
|
8
|
+
export type MessageProblem = 'multiple_parts' | 'ambiguous_headers' | 'transfer_encoding' | 'media_type' | 'not_partial_representation' | 'invalid_description' | 'unreadable';
|
|
9
|
+
/** What a message carries: no MAP part, an unusable one and why, or its description. */
|
|
10
|
+
export type MessageResult = {
|
|
11
|
+
status: 'none';
|
|
12
|
+
} | {
|
|
13
|
+
status: 'invalid';
|
|
14
|
+
reason: MessageProblem;
|
|
15
|
+
} | {
|
|
16
|
+
status: 'valid';
|
|
17
|
+
description: Description;
|
|
18
|
+
bytes: Uint8Array;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The MAP part of a received email (Core, "Email representation"), read from its original
|
|
22
|
+
* bytes: the one designated description of this profile, in a multipart/related entity whose
|
|
23
|
+
* root is the readable content it describes. A description inside an attachment or an
|
|
24
|
+
* attached message is never read. It never throws for untrusted input. `bytes` are the
|
|
25
|
+
* description exactly as the part carries it, after its transfer encoding is removed.
|
|
26
|
+
*/
|
|
27
|
+
export declare function extractMessage(input: string | Uint8Array): MessageResult;
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { PROFILE } from "./artifacts.js";
|
|
2
|
+
import { parseDescription } from "./description.js";
|
|
3
|
+
import { InvalidDocument } from "./json.js";
|
|
4
|
+
const READABLE = new Set(['text/plain', 'text/html']);
|
|
5
|
+
const TRANSFER_ENCODINGS = new Set(['base64', 'quoted-printable']);
|
|
6
|
+
const SINGLE_FIELDS = ['content-type', 'content-purpose', 'content-transfer-encoding'];
|
|
7
|
+
const FIELD = /^([!-9;-~]+):[ \t]*([\s\S]*)$/;
|
|
8
|
+
const PARAMETER = /^\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)\s*=/;
|
|
9
|
+
/**
|
|
10
|
+
* The MAP part of a received email (Core, "Email representation"), read from its original
|
|
11
|
+
* bytes: the one designated description of this profile, in a multipart/related entity whose
|
|
12
|
+
* root is the readable content it describes. A description inside an attachment or an
|
|
13
|
+
* attached message is never read. It never throws for untrusted input. `bytes` are the
|
|
14
|
+
* description exactly as the part carries it, after its transfer encoding is removed.
|
|
15
|
+
*/
|
|
16
|
+
export function extractMessage(input) {
|
|
17
|
+
try {
|
|
18
|
+
const raw = typeof input === 'string' ? input : binary(input);
|
|
19
|
+
const designated = entities(entity(raw)).filter(([part]) => isDesignated(part));
|
|
20
|
+
if (!designated.length)
|
|
21
|
+
return { status: 'none' };
|
|
22
|
+
if (designated.length > 1)
|
|
23
|
+
return invalid('multiple_parts');
|
|
24
|
+
const [part, parent] = designated[0];
|
|
25
|
+
const reason = problem(part, parent);
|
|
26
|
+
if (reason)
|
|
27
|
+
return invalid(reason);
|
|
28
|
+
const bytes = decoded(part);
|
|
29
|
+
try {
|
|
30
|
+
return { status: 'valid', description: parseDescription(bytes), bytes };
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
if (error instanceof InvalidDocument)
|
|
34
|
+
return invalid('invalid_description');
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return invalid('unreadable');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function invalid(reason) {
|
|
43
|
+
return { status: 'invalid', reason };
|
|
44
|
+
}
|
|
45
|
+
// Every part with its parent, at any depth. An attachment or an attached message is a leaf,
|
|
46
|
+
// so nothing inside one is read.
|
|
47
|
+
function entities(parent) {
|
|
48
|
+
return parent.parts.flatMap((part) => attached(part) || part.mimeType === 'message/rfc822' ? [] : [[part, parent], ...entities(part)]);
|
|
49
|
+
}
|
|
50
|
+
// A designated part labelled with this profile, judged from its original header lines,
|
|
51
|
+
// before a parser picks one of repeated fields or parameters.
|
|
52
|
+
function isDesignated(part) {
|
|
53
|
+
const purposes = values(part, 'content-purpose');
|
|
54
|
+
if (!purposes.some((value) => value.trim().toLowerCase() === 'machine-readable'))
|
|
55
|
+
return false;
|
|
56
|
+
const types = values(part, 'content-type');
|
|
57
|
+
return types.some((value) => value.toLowerCase().includes('application/ld+json')) && types.some((value) => value.includes(PROFILE));
|
|
58
|
+
}
|
|
59
|
+
function problem(part, parent) {
|
|
60
|
+
if (!unambiguous(part))
|
|
61
|
+
return 'ambiguous_headers';
|
|
62
|
+
if (!TRANSFER_ENCODINGS.has(first(part, 'content-transfer-encoding').trim().toLowerCase()))
|
|
63
|
+
return 'transfer_encoding';
|
|
64
|
+
if (part.mimeType !== 'application/ld+json' || part.parameters.get('profile') !== PROFILE)
|
|
65
|
+
return 'media_type';
|
|
66
|
+
if (!partialRepresentation(parent))
|
|
67
|
+
return 'not_partial_representation';
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
// Each field that decides how the part is read appears once, with each parameter once.
|
|
71
|
+
function unambiguous(part) {
|
|
72
|
+
if (!part.fields)
|
|
73
|
+
return false;
|
|
74
|
+
const counts = new Map();
|
|
75
|
+
for (const [name] of part.fields)
|
|
76
|
+
counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
77
|
+
return SINGLE_FIELDS.every((name) => counts.get(name) === 1) && uniqueParameters(first(part, 'content-type'));
|
|
78
|
+
}
|
|
79
|
+
// A multipart/related entity with one unambiguous Content-Type, whose root (its start
|
|
80
|
+
// parameter's part, or else its first) is readable.
|
|
81
|
+
function partialRepresentation(parent) {
|
|
82
|
+
if (parent.mimeType !== 'multipart/related')
|
|
83
|
+
return false;
|
|
84
|
+
const types = values(parent, 'content-type');
|
|
85
|
+
if (types.length !== 1 || !uniqueParameters(types[0]))
|
|
86
|
+
return false;
|
|
87
|
+
const start = parent.parameters.get('start') ?? '';
|
|
88
|
+
const roots = start ? parent.parts.filter((part) => first(part, 'content-id').trim() === start) : parent.parts.slice(0, 1);
|
|
89
|
+
return roots.length === 1 && readable(roots[0]);
|
|
90
|
+
}
|
|
91
|
+
function readable(part) {
|
|
92
|
+
if (attached(part))
|
|
93
|
+
return false;
|
|
94
|
+
if (part.mimeType === 'multipart/alternative')
|
|
95
|
+
return part.parts.some(readable);
|
|
96
|
+
return READABLE.has(part.mimeType) && binary(decoded(part)).trim().length > 0;
|
|
97
|
+
}
|
|
98
|
+
function attached(part) {
|
|
99
|
+
return first(part, 'content-disposition').trim().toLowerCase().startsWith('attachment');
|
|
100
|
+
}
|
|
101
|
+
function values(part, name) {
|
|
102
|
+
return (part.fields ?? []).filter(([field]) => field === name).map(([, value]) => value);
|
|
103
|
+
}
|
|
104
|
+
function first(part, name) {
|
|
105
|
+
return values(part, name)[0] ?? '';
|
|
106
|
+
}
|
|
107
|
+
// One entity from its raw bytes (a binary string, one character per byte): its header,
|
|
108
|
+
// Content-Type and, for a multipart entity, its parts.
|
|
109
|
+
function entity(raw) {
|
|
110
|
+
const fields = headerFields(raw);
|
|
111
|
+
const body = split(raw)?.[1] ?? '';
|
|
112
|
+
const contentType = (fields ?? []).find(([name]) => name === 'content-type')?.[1] ?? 'text/plain';
|
|
113
|
+
const [type, ...rest] = segments(contentType) ?? [contentType];
|
|
114
|
+
const mimeType = type.trim().toLowerCase();
|
|
115
|
+
const parameters = new Map();
|
|
116
|
+
for (const segment of rest) {
|
|
117
|
+
const name = PARAMETER.exec(segment)?.[1];
|
|
118
|
+
if (!name)
|
|
119
|
+
continue;
|
|
120
|
+
const key = name.toLowerCase();
|
|
121
|
+
if (!parameters.has(key))
|
|
122
|
+
parameters.set(key, unquote(segment.slice(segment.indexOf('=') + 1).trim()));
|
|
123
|
+
}
|
|
124
|
+
const boundary = parameters.get('boundary');
|
|
125
|
+
const parts = mimeType.startsWith('multipart/') && boundary ? multipart(body, boundary).map(entity) : [];
|
|
126
|
+
return { fields, mimeType, parameters, body, parts };
|
|
127
|
+
}
|
|
128
|
+
// The raw bytes of each body part between the boundary's delimiter lines; the preamble and
|
|
129
|
+
// epilogue are not parts.
|
|
130
|
+
function multipart(body, boundary) {
|
|
131
|
+
const delimiter = `--${boundary}`;
|
|
132
|
+
const parts = [];
|
|
133
|
+
let current = null;
|
|
134
|
+
// The line break before a delimiter line belongs to the delimiter, not to the part.
|
|
135
|
+
const close = () => {
|
|
136
|
+
if (current)
|
|
137
|
+
parts.push(current.join('').replace(/\r?\n$/, ''));
|
|
138
|
+
};
|
|
139
|
+
for (const line of body.split(/(?<=\n)/)) {
|
|
140
|
+
const content = line.replace(/\r?\n$/, '').replace(/[ \t]+$/, '');
|
|
141
|
+
if (content === `${delimiter}--`) {
|
|
142
|
+
close();
|
|
143
|
+
return parts;
|
|
144
|
+
}
|
|
145
|
+
if (content === delimiter) {
|
|
146
|
+
close();
|
|
147
|
+
current = [];
|
|
148
|
+
}
|
|
149
|
+
else
|
|
150
|
+
current?.push(line);
|
|
151
|
+
}
|
|
152
|
+
close();
|
|
153
|
+
return parts;
|
|
154
|
+
}
|
|
155
|
+
// An entity's header block and body, split at the first empty line; a part that begins with
|
|
156
|
+
// an empty line has no header fields. Null when there is no empty line.
|
|
157
|
+
function split(raw) {
|
|
158
|
+
const leading = /^\r?\n/.exec(raw);
|
|
159
|
+
if (leading)
|
|
160
|
+
return ['', raw.slice(leading[0].length)];
|
|
161
|
+
const separator = /\r?\n\r?\n/.exec(raw);
|
|
162
|
+
return separator ? [raw.slice(0, separator.index), raw.slice(separator.index + separator[0].length)] : null;
|
|
163
|
+
}
|
|
164
|
+
// The unfolded fields of an entity's header block as [lowercase name, value] pairs, or null
|
|
165
|
+
// when it is malformed. Lines end with CRLF or LF.
|
|
166
|
+
function headerFields(raw) {
|
|
167
|
+
const parts = split(raw);
|
|
168
|
+
if (!parts)
|
|
169
|
+
return null;
|
|
170
|
+
const lines = parts[0] ? parts[0].split(/\r?\n/) : [];
|
|
171
|
+
const fields = [];
|
|
172
|
+
for (const line of lines) {
|
|
173
|
+
if (/[\r\n]/.test(line))
|
|
174
|
+
return null;
|
|
175
|
+
if (line.startsWith(' ') || line.startsWith('\t')) {
|
|
176
|
+
if (!fields.length)
|
|
177
|
+
return null;
|
|
178
|
+
fields[fields.length - 1][1] += ` ${line.trim()}`;
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
const match = FIELD.exec(line);
|
|
182
|
+
if (!match)
|
|
183
|
+
return null;
|
|
184
|
+
fields.push([match[1].toLowerCase(), match[2]]);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return fields;
|
|
188
|
+
}
|
|
189
|
+
// Whether every parameter of a Content-Type value has its own name. RFC 2231 sections and
|
|
190
|
+
// charset markers belong to the name they extend, so profile and profile* are one name.
|
|
191
|
+
function uniqueParameters(value) {
|
|
192
|
+
const parts = segments(value);
|
|
193
|
+
if (!parts)
|
|
194
|
+
return false;
|
|
195
|
+
const names = [];
|
|
196
|
+
for (const segment of parts.slice(1)) {
|
|
197
|
+
const name = PARAMETER.exec(segment)?.[1];
|
|
198
|
+
if (!name)
|
|
199
|
+
return false;
|
|
200
|
+
names.push(name.toLowerCase().replace(/\*.*$/, ''));
|
|
201
|
+
}
|
|
202
|
+
return new Set(names).size === names.length;
|
|
203
|
+
}
|
|
204
|
+
// The value split at each semicolon outside a quoted string, or null when a quoted string or
|
|
205
|
+
// an escape is left open.
|
|
206
|
+
function segments(value) {
|
|
207
|
+
const parts = [''];
|
|
208
|
+
let quoted = false;
|
|
209
|
+
let escaped = false;
|
|
210
|
+
for (const char of value) {
|
|
211
|
+
if (char === ';' && !quoted) {
|
|
212
|
+
parts.push('');
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (escaped)
|
|
216
|
+
escaped = false;
|
|
217
|
+
else if (quoted && char === '\\')
|
|
218
|
+
escaped = true;
|
|
219
|
+
else if (char === '"')
|
|
220
|
+
quoted = !quoted;
|
|
221
|
+
parts[parts.length - 1] += char;
|
|
222
|
+
}
|
|
223
|
+
return quoted || escaped ? null : parts;
|
|
224
|
+
}
|
|
225
|
+
function unquote(value) {
|
|
226
|
+
return value.startsWith('"') && value.endsWith('"') && value.length >= 2
|
|
227
|
+
? value.slice(1, -1).replace(/\\(.)/g, '$1')
|
|
228
|
+
: value;
|
|
229
|
+
}
|
|
230
|
+
// The part's body with its transfer encoding removed.
|
|
231
|
+
function decoded(part) {
|
|
232
|
+
const encoding = first(part, 'content-transfer-encoding').trim().toLowerCase();
|
|
233
|
+
if (encoding === 'base64')
|
|
234
|
+
return base64(part.body);
|
|
235
|
+
if (encoding === 'quoted-printable')
|
|
236
|
+
return quotedPrintable(part.body);
|
|
237
|
+
return bytesOf(part.body);
|
|
238
|
+
}
|
|
239
|
+
// Characters outside the alphabet are skipped, as mail readers do, so a damaged body reads as
|
|
240
|
+
// an invalid description rather than an unreadable message.
|
|
241
|
+
function base64(body) {
|
|
242
|
+
let clean = body.replace(/[^A-Za-z0-9+/]/g, '');
|
|
243
|
+
if (clean.length % 4 === 1)
|
|
244
|
+
clean = clean.slice(0, -1);
|
|
245
|
+
return bytesOf(atob(clean.padEnd(Math.ceil(clean.length / 4) * 4, '=')));
|
|
246
|
+
}
|
|
247
|
+
function quotedPrintable(body) {
|
|
248
|
+
const text = body.replace(/[ \t]+(?=\r?\n)/g, '').replace(/=\r?\n/g, '');
|
|
249
|
+
return bytesOf(text.replace(/=([0-9A-Fa-f]{2})/g, (_match, hex) => String.fromCharCode(parseInt(hex, 16))));
|
|
250
|
+
}
|
|
251
|
+
function binary(bytes) {
|
|
252
|
+
let text = '';
|
|
253
|
+
for (let index = 0; index < bytes.length; index += 0x8000)
|
|
254
|
+
text += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
|
|
255
|
+
return text;
|
|
256
|
+
}
|
|
257
|
+
function bytesOf(text) {
|
|
258
|
+
const bytes = new Uint8Array(text.length);
|
|
259
|
+
for (let index = 0; index < text.length; index += 1)
|
|
260
|
+
bytes[index] = text.charCodeAt(index) & 0xff;
|
|
261
|
+
return bytes;
|
|
262
|
+
}
|