Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 93 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
[![npm](https://img.shields.io/npm/v/mailschema)](https://www.npmjs.com/package/mailschema)
[![CI](https://github.com/mailschema/javascript/actions/workflows/test.yml/badge.svg)](https://github.com/mailschema/javascript/actions/workflows/test.yml)

The Mail Action Protocol 0.2 core artifacts, and local validation of MailSchema Registry contributions, with no network requests.
Mail Action Protocol 0.2 for JavaScript and TypeScript. The package parses, canonicalizes, digests and validates MAP documents, verifies the type contracts an implementation vendors, and builds results and problems. It also carries the MAP 0.2 core artifacts and validates MailSchema Registry contributions locally.

It does not establish endpoint trust, verify email authentication, grant authority or send email. Possession mode needs DKIM and DMARC checks on the raw message, which this package leaves to the client.

[Specification](https://mailschema.org/specification) · [Registry](https://mailschema.org/registry) · [Tools](https://mailschema.org/tools) · [Source](https://github.com/mailschema/javascript)

Expand All @@ -15,19 +17,101 @@ npm install mailschema

Node.js 22 or newer is required. The package is ESM and includes TypeScript declarations.

## A service

Vendor the exact contract and request schema your service implements, and pin the contract by the digest you reviewed. The package refuses any other contract.

```ts
import { readFileSync } from 'node:fs';
import { Contract, digest } from 'mailschema';

const read = (path: string) => JSON.parse(readFileSync(path, 'utf8'));
const contract = new Contract(
read('mailschema/content-review-0.3.json'),
read('mailschema/content-review-0.3.schema.json'),
{ digest: 'sha-256:…' },
);
```

Before sending a description, check it against every rule of the core and the contract, and store its digest or keep it rebuildable from the interaction:

```ts
contract.descriptionErrors(description); // []
digest(description); // 'sha-256:…'
```

When a request arrives, check it in this order. No step applies an effect for a problem, and a refusal before the description is resolved and its digest matched leaves the request identifier unclaimed:

```ts
import { isJsonRequest, parse, problem, requestErrors, result, resultUrl } from 'mailschema';
import type { MapRequest } from 'mailschema';

// Answer 415 unless isJsonRequest(contentType). Under possession authority, answer an
// unknown capability with a plain 404 and a lapsed one with a plain 410 before reading
// the body; under credential authority, authenticate the principal.
const request = parse(body) as MapRequest; // throws InvalidDocument
requestErrors(request); // any errors: invalid-request

// Resolve the description you issued for request.interactionId. Refuse an unknown
// interaction, or a request whose descriptionDigest is not digest(description).

// Request identifiers are claimed within your tenant: the account, or the capability.
// If request.requestId is already claimed there, refuse another principal, and a principal
// whose permission has been revoked, with an uncorrelated refused problem (problem()
// without requestId). Answer any change to the request, compared by digest, with
// idempotency-conflict. Otherwise settle the recorded result with settle() and return it,
// or expired-interaction once retainUntil() has passed. Nothing is applied again.

const refused = contract.requestProblem(description, request, { now: new Date() });
// refused.code is unsupported-type, unsupported-operation or expired-interaction, with the
// title and detail problem() takes. Then your own state: already-decided, or stale-target.

contract.inputErrors(description, request);
// [{ detail: '…', pointer: '/feedback' }], a claimed invalid-request
```

Then apply the approval lifecycle or the effect, and record the result:

```ts
result(request, {
state: 'accepted',
target: description.target,
resultUrl: resultUrl(description, request.requestId),
recordedAt: new Date(),
output: { feedbackRecorded: true, feedbackId: 'fb-1' },
});
```

## API

| Call | Does |
| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `parse(text \| bytes)` | Parses a MAP document as I-JSON within the core limits, or throws `InvalidDocument` |
| `canonicalize(value)`, `digest(value)` | RFC 8785 canonical JSON, and `sha-256:` over it |
| `mapErrors(document)` | Checks a description, request, result or problem against the core schema |
| `descriptionErrors`, `requestErrors`, `resultErrors`, `problemErrors` | Check one document against its core definition only |
| `new Contract(contract, requestSchema, { digest, dependencies })` | Checks the contract's format and profile, refuses any contract but the one pinned by `digest`, checks its pinned dependencies and request schema, and compiles every validator once, or throws `InvalidContract`; `dependencies` supplies, by URL, any pinned schema the package does not bundle |
| `contract.descriptionErrors(description)` | Checks a description against every rule of the core and the contract |
| `contract.requestProblem(description, request, { now })` | The exact type, an offered operation the authority permits, and expiry, as a problem code, title and detail, or undefined |
| `contract.inputErrors(description, request)` | Checks an operation's input and field bindings, with JSON Pointers into `input` |
| `contract.requestErrors(request)`, `contract.resultErrors(result)` | Check a request against the core and the request schema, and a result against the core, the declared output schema and the declared reason |
| `contract.typeReference`, `contract.operation(id)`, `contract.isDecision(id)` | The type reference descriptions and requests name, one of its operations, and whether completing it decides the interaction |
| `result`, `transition`, `problem` | Build results, state transitions and problems with their correlation members, or throw rather than return a document the core refuses. A problem stays within the core limits |
| `resultUrl`, `resultStatus`, `isRequestId` | The result resource of a request, a result's HTTP status, and whether a value is a request identifier, the only thing a result URL names |
| `isJsonRequest(contentType)` | Whether a `Content-Type` admits a request rather than a 415 |
| `DESCRIPTION_MEDIA_TYPE`, `isDescriptionPart(mediaType, profileParameter)` | The `Content-Type` of the part that carries a description, and whether a designated part is labelled with this profile |
| `retainUntil`, `settle`, `reached` | Result retention, the expiry of an undecided approval, and whether a deadline has passed |
| `capability(description)`, `writtenPath(url)` | The possession capability: the last segment of the execution URL's path as written |

Type rules a contract cannot express, such as a meeting slot being one of the slots offered, belong to each type's implementation. Validation uses Ajv with JSON Schema 2020-12. Lexical forms are core schema patterns, so `format` is never asserted, and references resolve only against pinned schemas, never over the network.

## MAP 0.2 core artifacts

```js
import {
MAP_PROFILE,
getContractFormatSchema,
getFormsSchema,
getMapContext,
getMapSchema,
} from 'mailschema';
import { getContractFormatSchema, getFormsSchema, getMapContext, getMapSchema } from 'mailschema';
```

Each is byte-identical to the file the [profile record](https://mailschema.org/profiles/map/0.2.json) binds by SHA-256, and is also exported raw as `mailschema/map-0.2.schema.json`, `mailschema/map-0.2.jsonld`, `mailschema/type-contract-0.2.schema.json` and `mailschema/forms-0.1.schema.json`. Type contracts are not bundled: a client obtains them from the [Registry catalogue](https://mailschema.org/registry/catalog.json) by digest. Processing MAP messages is outside this package; see the [profile](https://mailschema.org/specification/profile).
Each is byte-identical to the file the [profile record](https://mailschema.org/profiles/map/0.2.json) binds by SHA-256, and is also exported raw as `mailschema/map-0.2.schema.json`, `mailschema/map-0.2.jsonld`, `mailschema/type-contract-0.2.schema.json` and `mailschema/forms-0.1.schema.json`. Type contracts are not bundled: an implementation vendors the contracts it supports, and `Contract` verifies them by digest.

## Registry data

Expand Down
2 changes: 1 addition & 1 deletion UPSTREAM.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Release provenance

Version `0.2.1` derives from [`mailschema/mailschema@db99c15`](https://github.com/mailschema/mailschema/commit/db99c1582f68b3cd3e80d5fe6c029c8535bf470c).
Version `0.2.2` derives from [`mailschema/mailschema@48c5fd6`](https://github.com/mailschema/mailschema/commit/48c5fd6f189940beb0675f6c1340d5c4c8b3c592). Its `src/core` is that commit's `src/map/core`, the MAP core the reference implementation and conformance suite run on, with only the bundled artifact imports pointing at this package's copies.

The bundled files are exact projections of that source commit and do not independently define MAP:

Expand Down
36 changes: 36 additions & 0 deletions dist/core/artifacts.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { type ErrorObject, type ValidateFunction } from 'ajv/dist/2020.js';
import type { JsonObject } from './types.ts';
export declare const MAP_PROFILE = "https://mailschema.org/profiles/map/0.2";
export declare const CORE_SCHEMA = "https://mailschema.org/schemas/map-0.2.schema.json";
export declare const FORMS_SCHEMA = "https://mailschema.org/schemas/forms-0.1.schema.json";
export declare const CONTRACT_FORMAT = "https://mailschema.org/schemas/type-contract-0.2.schema.json";
export declare const CONTEXT = "https://mailschema.org/contexts/map-0.2.jsonld";
export declare const JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
/** The schemas a contract may depend on without supplying them itself. */
export declare const BUNDLED: ReadonlyMap<string, JsonObject>;
/** A core or form fields definition by name, for the shared lexical vectors. */
export declare const definition: (schema: string, name: string) => ValidateFunction;
/** Errors as `pointer message` lines, as the other MailSchema packages report them. */
export declare function errorList(errors: ErrorObject[] | null | undefined, prefix?: string): string[];
/** Checks a type contract against the contract format. */
export declare const contractFormatErrors: (contract: unknown) => string[];
/** Checks any MAP 0.2 description, request, result or problem against the core schema. */
export declare const mapErrors: (document: unknown) => string[];
/**
* Checks a description against the core description definition only. A description of a
* type the caller has no contract for can be checked this far.
*/
export declare const descriptionErrors: (description: unknown) => string[];
/** Checks a request against the core request definition. Its identifier stays free if it fails. */
export declare const requestErrors: (request: unknown) => string[];
/** Checks a result against the core result definition only. */
export declare const resultErrors: (result: unknown) => string[];
/** Checks a problem against the core problem definition, including its type, status and code. */
export declare const problemErrors: (problem: unknown) => string[];
/** Whether a value is a request identifier: the core UUID URN form. Only one names a result resource. */
export declare const isRequestId: (value: unknown) => boolean;
/**
* Whether a deadline, a core date-time plus `afterSeconds`, has been reached. Anything but
* a core date-time counts as reached, so a mistake fails closed.
*/
export declare const reached: (now: Date, deadline: string, afterSeconds?: number) => boolean;
78 changes: 78 additions & 0 deletions dist/core/artifacts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// The bundled core artifacts and the validators built from them.
import Ajv2020 from 'ajv/dist/2020.js';
import { contractFormat, coreSchema, formsSchema } from "./bundled.js";
export const MAP_PROFILE = 'https://mailschema.org/profiles/map/0.2';
export const CORE_SCHEMA = 'https://mailschema.org/schemas/map-0.2.schema.json';
export const FORMS_SCHEMA = 'https://mailschema.org/schemas/forms-0.1.schema.json';
export const CONTRACT_FORMAT = 'https://mailschema.org/schemas/type-contract-0.2.schema.json';
export const CONTEXT = 'https://mailschema.org/contexts/map-0.2.jsonld';
export const JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema';
/** The schemas a contract may depend on without supplying them itself. */
export const BUNDLED = new Map([
[CORE_SCHEMA, coreSchema],
[FORMS_SCHEMA, formsSchema],
]);
/**
* JSON Schema 2020-12 as MAP reads it. Lexical forms are the core schema's patterns, so
* `format` stays an annotation: format checkers differ between validators. References
* resolve only against schemas already added, never over the network.
* @internal
*/
export function createValidator() {
const ajv = new Ajv2020({
allErrors: true,
strict: true,
strictRequired: false,
validateFormats: false,
});
// HTML autofill field names label form fields; they are annotations, not assertions.
ajv.addKeyword({ keyword: 'autocomplete', schemaType: 'string' });
// Only JSON Schema 2020-12 vocabulary keywords. Ajv also reads OpenAPI's `nullable`,
// which admits a null other validators refuse, and the earlier `dependencies` and
// `definitions`; strict mode now refuses them as unknown.
for (const keyword of ['nullable', 'dependencies', 'definitions'])
ajv.removeKeyword(keyword);
for (const schema of BUNDLED.values())
ajv.addSchema(schema);
return ajv;
}
const core = createValidator();
/** A core or form fields definition by name, for the shared lexical vectors. */
export const definition = (schema, name) => core.getSchema(`${schema}#/$defs/${name}`);
/** Errors as `pointer message` lines, as the other MailSchema packages report them. */
export function errorList(errors, prefix = '') {
return (errors ?? [])
.slice(0, 100)
.map((error) => `${prefix + error.instancePath || '/'} ${error.message}${error.keyword === 'required' ? `: ${error.params.missingProperty}` : ''}`);
}
const errorsOf = (validate, value) => validate(value) ? [] : errorList(validate.errors);
const DOCUMENT = core.getSchema(CORE_SCHEMA);
const DEFINITIONS = Object.fromEntries(['description', 'request', 'result', 'problem'].map((name) => [
name,
definition(CORE_SCHEMA, name),
]));
const DATE_TIME = new RegExp(coreSchema.$defs.dateTime.pattern, 'u');
const REQUEST_ID = definition(CORE_SCHEMA, 'uuidUrn');
const CONTRACT = core.compile(contractFormat);
/** Checks a type contract against the contract format. */
export const contractFormatErrors = (contract) => errorsOf(CONTRACT, contract);
/** Checks any MAP 0.2 description, request, result or problem against the core schema. */
export const mapErrors = (document) => errorsOf(DOCUMENT, document);
/**
* Checks a description against the core description definition only. A description of a
* type the caller has no contract for can be checked this far.
*/
export const descriptionErrors = (description) => errorsOf(DEFINITIONS.description, description);
/** Checks a request against the core request definition. Its identifier stays free if it fails. */
export const requestErrors = (request) => errorsOf(DEFINITIONS.request, request);
/** Checks a result against the core result definition only. */
export const resultErrors = (result) => errorsOf(DEFINITIONS.result, result);
/** Checks a problem against the core problem definition, including its type, status and code. */
export const problemErrors = (problem) => errorsOf(DEFINITIONS.problem, problem);
/** Whether a value is a request identifier: the core UUID URN form. Only one names a result resource. */
export const isRequestId = (value) => REQUEST_ID(value);
/**
* Whether a deadline, a core date-time plus `afterSeconds`, has been reached. Anything but
* a core date-time counts as reached, so a mistake fails closed.
*/
export const reached = (now, deadline, afterSeconds = 0) => !(DATE_TIME.test(deadline) && now.getTime() < Date.parse(deadline) + afterSeconds * 1000);
Loading
Loading