mailschema 0.3.2 → 0.3.3
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 +17 -7
- package/bin/mailschema.js +73 -28
- package/dist/core/artifacts.js +39 -4
- package/dist/core/description.d.ts +3 -2
- package/dist/core/description.js +11 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,9 +3,11 @@
|
|
|
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.3
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
+
It needs Node.js 22 or later, as `engines` declares; browsers and workers run it as they are.
|
|
10
|
+
|
|
9
11
|
## Check a description against its contract
|
|
10
12
|
|
|
11
13
|
```js
|
|
@@ -20,7 +22,15 @@ if (errors.length) throw new Error(errors.join('\n'));
|
|
|
20
22
|
|
|
21
23
|
`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
24
|
|
|
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/`,
|
|
25
|
+
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/`, `exampleHref` is an example description of the type, and its Registry page is `href`.
|
|
26
|
+
|
|
27
|
+
## Write a description
|
|
28
|
+
|
|
29
|
+
Start from the type's example. A description has these members, all required: `@context`, `@type` (`MailAction`), `@id`, `profile`, `type` (`id`, `version`, `contractDigest`), `issuedAt`, `expiresAt`, `inLanguage` (a BCP 47 tag such as `en`), `service` (`id`, an HTTPS origin with no path, and an optional `tenant`), `recipient`, `subject` (`id`, `title`), `terms` (`id`, `version`), `details` (the shape the contract's `detailsSchema` sets), `operations` and `human` (`url`). Times are UTC to the second, `YYYY-MM-DDTHH:MM:SSZ`. `type.contractDigest` is the contract's digest: the second line `mailschema contract <contract.json>` prints, and the type's `digest` in the Registry.
|
|
30
|
+
|
|
31
|
+
## What a check covers
|
|
32
|
+
|
|
33
|
+
`parseDescription` and `Contract.descriptionErrors` check the document: the core rules, and that `details` and the operations are what the contract allows. They do not check what only the acting service knows. Whether the service, recipient, `details` and terms match a request recorded when the person started it (for an Email Address Confirmation, that `details.mailbox` is the recipient's mailbox), whether the current time is between `issuedAt` and `expiresAt`, and whether the message is authentic are the implementation's checks, under the contract's requirements and the [specification](https://mailschema.org/specification/core).
|
|
24
34
|
|
|
25
35
|
## API
|
|
26
36
|
|
|
@@ -37,13 +47,13 @@ The profile record, context and schemas are exported byte for byte: `mailschema/
|
|
|
37
47
|
## Command line
|
|
38
48
|
|
|
39
49
|
```sh
|
|
40
|
-
npx mailschema@0.3.
|
|
41
|
-
npx mailschema@0.3.
|
|
42
|
-
npx mailschema@0.3.
|
|
43
|
-
npx mailschema@0.3.
|
|
50
|
+
npx mailschema@0.3.3 contract campaign-send-approval-0.1.json
|
|
51
|
+
npx mailschema@0.3.3 description description.json --contract campaign-send-approval-0.1.json
|
|
52
|
+
npx mailschema@0.3.3 implementation record.json
|
|
53
|
+
npx mailschema@0.3.3 message approval.eml > description.json
|
|
44
54
|
```
|
|
45
55
|
|
|
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.
|
|
56
|
+
`mailschema <command> --help` explains one command, `--version` prints the package version, and `--json` prints the result as one JSON object: `{"valid":true,...}` with the identifiers and digest, or `{"valid":false,"errors":[...]}`. 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: each names the JSON Pointer to fix, and where a schema offers alternatives, only the one the value chose. Nothing is uploaded or changed.
|
|
47
57
|
|
|
48
58
|
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).
|
|
49
59
|
|
package/bin/mailschema.js
CHANGED
|
@@ -4,6 +4,7 @@ import { parseArgs } from 'node:util';
|
|
|
4
4
|
import {
|
|
5
5
|
Contract,
|
|
6
6
|
CONTRACT_MAX_BYTES,
|
|
7
|
+
DESCRIPTION_MAX_BYTES,
|
|
7
8
|
digest,
|
|
8
9
|
extractMessage,
|
|
9
10
|
InvalidDocument,
|
|
@@ -11,28 +12,53 @@ import {
|
|
|
11
12
|
parseImplementation,
|
|
12
13
|
} from '../dist/index.js';
|
|
13
14
|
|
|
14
|
-
const
|
|
15
|
+
const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
|
|
15
16
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
const COMMANDS = {
|
|
18
|
+
contract: {
|
|
19
|
+
usage: 'mailschema contract <contract.json>',
|
|
20
|
+
about: `Checks a type contract and prints "Valid type contract <id> <version>" and the
|
|
21
|
+
contract's digest. type.contractDigest in a description names this digest.`,
|
|
22
|
+
},
|
|
23
|
+
description: {
|
|
24
|
+
usage: 'mailschema description <description.json> [--contract <contract.json>]',
|
|
25
|
+
about: `Checks a description against MAP 0.3 Core and, with --contract, that it uses that
|
|
26
|
+
contract as it allows: its details and operations. Prints "Valid MAP 0.3 description
|
|
27
|
+
<@id>" and the description's digest, which is not the contract digest it names. It
|
|
28
|
+
checks the document only: whether the service, recipient and terms match a request
|
|
29
|
+
recorded when the person started it, and whether the description is still in its
|
|
30
|
+
issuedAt to expiresAt window, are for the implementation that acts on it.`,
|
|
31
|
+
},
|
|
32
|
+
implementation: {
|
|
33
|
+
usage: 'mailschema implementation <record.json>',
|
|
34
|
+
about: 'Checks a Registry implementation record and names the service it describes.',
|
|
35
|
+
},
|
|
36
|
+
message: {
|
|
37
|
+
usage: 'mailschema message <message.eml>',
|
|
38
|
+
about: `Finds a received email's one MAP part, writes its description to standard output
|
|
39
|
+
exactly as the part carries it, and prints the description's digest on standard error.`,
|
|
40
|
+
},
|
|
41
|
+
};
|
|
20
42
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
43
|
+
const help = `Mail Action Protocol 0.3 checks, mailschema ${version}
|
|
44
|
+
|
|
45
|
+
${Object.values(COMMANDS)
|
|
46
|
+
.map((command) => ` ${command.usage}`)
|
|
47
|
+
.join('\n')}
|
|
48
|
+
|
|
49
|
+
Options: --json prints the result as JSON, --help after a command explains it, and
|
|
50
|
+
--version prints the package version. A digest is the SHA-256 of the document's RFC 8785
|
|
51
|
+
canonical JSON. Nothing is uploaded or changed. An invalid document prints every reason
|
|
52
|
+
it is not valid, one per line, and exits 1.`;
|
|
53
|
+
|
|
54
|
+
const commandHelp = (name) => `${COMMANDS[name].usage}\n\n${COMMANDS[name].about}\n\nAdd --json for a JSON result.`;
|
|
28
55
|
|
|
29
56
|
// A whole email, attachments included, is far larger than any MAP document.
|
|
30
57
|
const MESSAGE_MAX_BYTES = 26214400;
|
|
31
58
|
|
|
32
|
-
async function read(path, maxBytes
|
|
59
|
+
async function read(path, maxBytes, kind) {
|
|
33
60
|
const info = await stat(path);
|
|
34
|
-
if (!info.isFile() || info.size > maxBytes)
|
|
35
|
-
throw new Error(`Expected ${kind} of at most ${maxBytes} bytes.`);
|
|
61
|
+
if (!info.isFile() || info.size > maxBytes) throw new Error(`Expected ${kind} of at most ${maxBytes} bytes.`);
|
|
36
62
|
return new Uint8Array(await readFile(path));
|
|
37
63
|
}
|
|
38
64
|
|
|
@@ -41,34 +67,53 @@ function report(errors) {
|
|
|
41
67
|
throw new InvalidDocument('Not valid.', errors);
|
|
42
68
|
}
|
|
43
69
|
|
|
70
|
+
let json = false;
|
|
44
71
|
try {
|
|
45
72
|
const { values, positionals } = parseArgs({
|
|
46
73
|
allowPositionals: true,
|
|
47
|
-
options: {
|
|
74
|
+
options: {
|
|
75
|
+
contract: { type: 'string' },
|
|
76
|
+
json: { type: 'boolean' },
|
|
77
|
+
help: { type: 'boolean', short: 'h' },
|
|
78
|
+
version: { type: 'boolean', short: 'v' },
|
|
79
|
+
},
|
|
48
80
|
});
|
|
81
|
+
json = Boolean(values.json);
|
|
49
82
|
const [command, path, ...extra] = positionals;
|
|
50
|
-
if (values.
|
|
83
|
+
if (values.version) console.log(version);
|
|
84
|
+
else if (values.help && Object.hasOwn(COMMANDS, command ?? '')) console.log(commandHelp(command));
|
|
85
|
+
else if (values.help || !command) console.log(help);
|
|
86
|
+
else if (!Object.hasOwn(COMMANDS, command)) throw new Error(`Unknown command ${command}.\n\n${help}`);
|
|
51
87
|
else if (!path || extra.length || (values.contract && command !== 'description'))
|
|
52
|
-
throw new Error(
|
|
88
|
+
throw new Error(commandHelp(command));
|
|
53
89
|
else if (command === 'contract') {
|
|
54
|
-
const contract = Contract.parse(await read(path));
|
|
55
|
-
|
|
90
|
+
const contract = Contract.parse(await read(path, CONTRACT_MAX_BYTES, 'a contract file'));
|
|
91
|
+
if (json) print({ valid: true, id: contract.id, version: contract.version, digest: contract.digest });
|
|
92
|
+
else console.log(`Valid type contract ${contract.id} ${contract.version}\n${contract.digest}`);
|
|
56
93
|
} else if (command === 'description') {
|
|
57
|
-
const description = parseDescription(await read(path));
|
|
94
|
+
const description = parseDescription(await read(path, DESCRIPTION_MAX_BYTES, 'a description file'));
|
|
58
95
|
if (values.contract)
|
|
59
|
-
report(Contract.parse(await read(values.contract)).descriptionErrors(description));
|
|
60
|
-
|
|
96
|
+
report(Contract.parse(await read(values.contract, CONTRACT_MAX_BYTES, 'a contract file')).descriptionErrors(description));
|
|
97
|
+
if (json) print({ valid: true, id: description['@id'], digest: digest(description) });
|
|
98
|
+
else console.log(`Valid MAP 0.3 description ${description['@id']}\n${digest(description)}`);
|
|
61
99
|
} else if (command === 'message') {
|
|
62
100
|
const result = extractMessage(await read(path, MESSAGE_MAX_BYTES, 'an email file'));
|
|
63
101
|
if (result.status === 'none') throw new Error('The message has no MAP 0.3 part.');
|
|
64
102
|
if (result.status === 'invalid') throw new Error(`The message's MAP part cannot be used: ${result.reason}.`);
|
|
65
103
|
process.stdout.write(result.bytes);
|
|
66
104
|
console.error(`Valid MAP 0.3 description ${result.description['@id']}\n${digest(result.description)}`);
|
|
67
|
-
} else
|
|
68
|
-
const record = parseImplementation(await read(path));
|
|
69
|
-
|
|
70
|
-
|
|
105
|
+
} else {
|
|
106
|
+
const record = parseImplementation(await read(path, CONTRACT_MAX_BYTES, 'a record file'));
|
|
107
|
+
if (json) print({ valid: true, service: record.service });
|
|
108
|
+
else console.log(`Valid implementation record for ${record.service}`);
|
|
109
|
+
}
|
|
71
110
|
} catch (error) {
|
|
72
|
-
|
|
111
|
+
const errors = error instanceof InvalidDocument ? error.errors : [error.message];
|
|
112
|
+
if (json) print({ valid: false, errors });
|
|
113
|
+
else console.error(errors.join('\n'));
|
|
73
114
|
process.exitCode = 1;
|
|
74
115
|
}
|
|
116
|
+
|
|
117
|
+
function print(result) {
|
|
118
|
+
console.log(JSON.stringify(result));
|
|
119
|
+
}
|
package/dist/core/artifacts.js
CHANGED
|
@@ -27,14 +27,49 @@ export function createValidator() {
|
|
|
27
27
|
return ajv;
|
|
28
28
|
}
|
|
29
29
|
/**
|
|
30
|
-
* Each validation error as its JSON Pointer and message
|
|
31
|
-
* values it allows,
|
|
30
|
+
* Each validation error as its JSON Pointer and message, reduced to the ones that say what to
|
|
31
|
+
* fix: an enum or const error names the values it allows, an unexpected member is named, an
|
|
32
|
+
* if/then wrapper is left to the error inside it, and a oneOf whose branches are told apart by
|
|
33
|
+
* a const reports only the branch the value chose. @internal
|
|
32
34
|
*/
|
|
33
|
-
export const schemaErrors = (errors, prefix = '') => (errors ?? []).map((error) => `${prefix + error.instancePath || '/'}: ${schemaMessage(error)}`);
|
|
35
|
+
export const schemaErrors = (errors, prefix = '') => actionable(errors ?? []).map((error) => `${prefix + error.instancePath || '/'}: ${schemaMessage(error)}`);
|
|
34
36
|
function schemaMessage(error) {
|
|
35
37
|
if (error.keyword === 'enum')
|
|
36
|
-
return `must be one of ${error.params.allowedValues
|
|
38
|
+
return `must be one of ${listed(error.params.allowedValues)}`;
|
|
37
39
|
if (error.keyword === 'const')
|
|
38
40
|
return `must be ${JSON.stringify(error.params.allowedValue)}`;
|
|
41
|
+
if (error.keyword === 'additionalProperties')
|
|
42
|
+
return `must not have the member ${JSON.stringify(error.params.additionalProperty)}`;
|
|
39
43
|
return error.message;
|
|
40
44
|
}
|
|
45
|
+
const listed = (values) => values.map((value) => JSON.stringify(value)).join(', ');
|
|
46
|
+
function actionable(errors) {
|
|
47
|
+
let kept = errors.filter((error) => error.keyword !== 'if');
|
|
48
|
+
for (const oneOf of kept.filter((error) => error.keyword === 'oneOf' && !error.params.passingSchemas)) {
|
|
49
|
+
const branchOf = (error) => error.schemaPath.startsWith(`${oneOf.schemaPath}/`)
|
|
50
|
+
? Number(error.schemaPath.slice(oneOf.schemaPath.length + 1).split('/')[0])
|
|
51
|
+
: undefined;
|
|
52
|
+
const branches = new Map();
|
|
53
|
+
for (const error of kept) {
|
|
54
|
+
const branch = branchOf(error);
|
|
55
|
+
if (branch !== undefined)
|
|
56
|
+
branches.set(branch, [...(branches.get(branch) ?? []), error]);
|
|
57
|
+
}
|
|
58
|
+
// The discriminator: a const one level below the oneOf's value that a branch refused.
|
|
59
|
+
const discriminator = (branch) => branch.find((error) => error.keyword === 'const' &&
|
|
60
|
+
error.instancePath.startsWith(`${oneOf.instancePath}/`) &&
|
|
61
|
+
!error.instancePath.slice(oneOf.instancePath.length + 1).includes('/'));
|
|
62
|
+
const refused = [...branches.values()].map(discriminator);
|
|
63
|
+
const chosen = [...branches.keys()].filter((_, index) => !refused[index]);
|
|
64
|
+
const sharedPointer = refused.find(Boolean)?.instancePath;
|
|
65
|
+
if (chosen.length === 1 && refused.filter(Boolean).length === branches.size - 1) {
|
|
66
|
+
kept = kept.filter((error) => error !== oneOf && (branchOf(error) ?? chosen[0]) === chosen[0]);
|
|
67
|
+
}
|
|
68
|
+
else if (chosen.length === 0 && sharedPointer && refused.every((error) => error?.instancePath === sharedPointer)) {
|
|
69
|
+
const allowed = refused.map((error) => error.params.allowedValue);
|
|
70
|
+
const combined = { ...refused[0], keyword: 'enum', params: { allowedValues: allowed } };
|
|
71
|
+
kept = [...kept.filter((error) => error !== oneOf && branchOf(error) === undefined), combined];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return kept;
|
|
75
|
+
}
|
|
@@ -37,8 +37,9 @@ export interface Description {
|
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
39
|
* Why the value is not a MAP 0.3 description, or no reasons. Beyond the core schema:
|
|
40
|
-
* expiry follows issuance,
|
|
41
|
-
* identifier contains whitespace, a control or a
|
|
40
|
+
* expiry follows issuance, inLanguage is a well-formed BCP 47 tag, operation identifiers are
|
|
41
|
+
* unique, and no security-sensitive identifier contains whitespace, a control or a
|
|
42
|
+
* formatting character.
|
|
42
43
|
*/
|
|
43
44
|
export declare function descriptionErrors(value: unknown): string[];
|
|
44
45
|
/** The description in the bytes or text, or InvalidDocument with every reason it is not one. */
|
package/dist/core/description.js
CHANGED
|
@@ -4,10 +4,17 @@ import { InvalidDocument, parse } from "./json.js";
|
|
|
4
4
|
const validate = createValidator().compile(coreSchema);
|
|
5
5
|
// Whitespace, controls, bidirectional and invisible formatting characters.
|
|
6
6
|
const UNSAFE = /[\p{White_Space}\p{Cc}\p{Cf}]/u;
|
|
7
|
+
// A well-formed BCP 47 language tag: RFC 5646's langtag, privateuse and grandfathered forms.
|
|
8
|
+
const LANGUAGE_TAG = new RegExp('^(?:(?:[a-z]{2,3}(?:-[a-z]{3}){0,3}|[a-z]{4}|[a-z]{5,8})(?:-[a-z]{4})?(?:-(?:[a-z]{2}|[0-9]{3}))?' +
|
|
9
|
+
'(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*(?:-x(?:-[a-z0-9]{1,8})+)?' +
|
|
10
|
+
'|x(?:-[a-z0-9]{1,8})+' +
|
|
11
|
+
'|en-gb-oed|i-(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)' +
|
|
12
|
+
'|sgn-(?:be-fr|be-nl|ch-de)|art-lojban|cel-gaulish|no-(?:bok|nyn)|zh-(?:guoyu|hakka|min|min-nan|xiang))$', 'i');
|
|
7
13
|
/**
|
|
8
14
|
* Why the value is not a MAP 0.3 description, or no reasons. Beyond the core schema:
|
|
9
|
-
* expiry follows issuance,
|
|
10
|
-
* identifier contains whitespace, a control or a
|
|
15
|
+
* expiry follows issuance, inLanguage is a well-formed BCP 47 tag, operation identifiers are
|
|
16
|
+
* unique, and no security-sensitive identifier contains whitespace, a control or a
|
|
17
|
+
* formatting character.
|
|
11
18
|
*/
|
|
12
19
|
export function descriptionErrors(value) {
|
|
13
20
|
if (!validate(value))
|
|
@@ -15,6 +22,8 @@ export function descriptionErrors(value) {
|
|
|
15
22
|
const errors = [];
|
|
16
23
|
if (Date.parse(value.expiresAt) <= Date.parse(value.issuedAt))
|
|
17
24
|
errors.push('/expiresAt: must be later than issuedAt');
|
|
25
|
+
if (!LANGUAGE_TAG.test(value.inLanguage))
|
|
26
|
+
errors.push('/inLanguage: must be a well-formed BCP 47 language tag');
|
|
18
27
|
const ids = value.operations.map((operation) => operation.id);
|
|
19
28
|
if (new Set(ids).size !== ids.length)
|
|
20
29
|
errors.push('/operations: identifiers must be unique');
|