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
144 changes: 25 additions & 119 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,138 +1,44 @@
# MailSchema for JavaScript
# mailschema

[![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)

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)

## Install
[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.

```sh
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:…'
npm install mailschema@0.3.0
```

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).
## Check a description against its contract

// 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.
```js
import { readFile } from 'node:fs/promises';
import { Contract, parseDescription } from 'mailschema';

contract.inputErrors(description, request);
// [{ detail: '…', pointer: '/feedback' }], a claimed invalid-request
const contract = Contract.parse(await readFile('campaign-send-approval-0.1.json'));
const description = parseDescription(await readFile('description.json'));
const errors = contract.descriptionErrors(description);
if (errors.length) throw new Error(errors.join('\n'));
```

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' },
});
```
`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.

## 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 |
- `parse(input, maxBytes)`, `canonicalize(value)`, `digest(value)`: MAP JSON and RFC 8785 digests.
- `descriptionErrors(value)`, `parseDescription(input)`: the core description rules.
- `new Contract(value)`, `Contract.parse(input)`: a checked contract with `digest`, `operation(id)`, `detailsErrors(details)`, `inputErrors(operationId, input)` and `descriptionErrors(description)`.
- `contractErrors(value)`: why a value is not a contract, including schema keywords, formats and patterns every implementation can enforce alike.
- `implementationErrors(value)`, `parseImplementation(input)`: Registry implementation records.
- `PROFILE`, `CONTEXT`, `DESCRIPTION_MEDIA_TYPE`, `EFFECTS`, `CAPABILITY_KINDS` and the size limits.

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 { 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: an implementation vendors the contracts it supports, and `Contract` verifies them by digest.

## Registry data

```js
import { assertContribution, contributionErrors, referenceErrors } from 'mailschema';

const errors = contributionErrors(candidate);
if (errors.length) console.error(errors);
else assertContribution(candidate);

const referenceProblems = referenceErrors(candidate, catalog);
```
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`.

`assertTypeRecord` and `getRecordSchema` handle expanded Registry records. Reference checks use a catalogue supplied by the caller; the package never fetches one.
## Command line

```sh
npx mailschema check contribution.json
npx mailschema check record.json --record
npx mailschema schema --map
npx mailschema@0.3.0 contract campaign-send-approval-0.1.json
npx mailschema@0.3.0 description description.json --contract campaign-send-approval-0.1.json
npx mailschema@0.3.0 implementation record.json
```

## Trust boundary
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).

A valid document is structured input. Validation does not authenticate a service, grant authority or establish product conformance. The CLI reads one local file of at most 256 KiB and does not upload or modify it. Package versions and MAP profile versions advance independently. MIT licensed.
Source: [mailschema/javascript](https://github.com/mailschema/javascript). License: MIT.
16 changes: 8 additions & 8 deletions UPSTREAM.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
# Release provenance

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.
Version `0.3.0` derives from [`mailschema/mailschema@2c26469`](https://github.com/mailschema/mailschema/commit/2c26469209070f04ff9f8ec29e1387b8699a46a0). Its sources, tests and bundled files are prepared from that commit by `npm run packages:prepare`.

The bundled files are exact projections of that source commit and do not independently define MAP:
The bundled MAP 0.3 artifacts are exact copies of that commit's files and do not independently define MAP:

- MAP 0.2 core schema: `732d60fcb758d945dc15c57d885c9d1c0c76423a7439096d9755e8ec9830836a`
- MAP 0.2 JSON-LD context: `dfed0189524d7d16d31ed3d8af97e9a0c458200c4c034b413f9d14fa35b60257`
- Type contract format: `e030007cc034662c9d9d448a8a035aff3106cfb96fb60e6aa9f92b99b25df0b9`
- Form fields block: `3a976b93a057380e3630ca05e77e221a43a98559fb7fda8066299ec4bf2a8f9e`
- Contribution schema: `a8a241b4837971a6251bcc135c704283536f4fb825fbbaedaf1598c6e688d564`
- profile (`dist/profile.json`): `d9481627f855c127a4f5d6ddb7f3b699f66f6475bc8672d609f5b499f83d1a0f`
- context (`dist/context.jsonld`): `a51490d1fe8af695c14ea508aad88fd0429d18564791b6b52f3ab07d5c51aab3`
- core-schema (`dist/core.schema.json`): `0ad09a6955a47e7a2c1c1eec0747a3e0b15c08a79860e90ce4e65da11983aeb3`
- contract-schema (`dist/contract.schema.json`): `86bf057529c4fd2c7f0a880825774afeed31e9f7ba1d99760858a585fe28d18d`
- implementation-schema (`dist/implementation.schema.json`): `c62acc3ebb9f384c8fba7be353ab1905b65883ac2b16b147fd98485eec643396`

The canonical artifacts live in the main MailSchema repository. This repository owns the JavaScript and TypeScript package surface and its release history.
The canonical artifacts live in the main MailSchema repository. This repository owns the JavaScript package and its release history.
10 changes: 5 additions & 5 deletions artifacts.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[
"contribution.schema.json",
"map-0.2.schema.json",
"map-0.2.jsonld",
"type-contract-0.2.schema.json",
"forms-0.1.schema.json"
"profile.json",
"context.jsonld",
"core.schema.json",
"contract.schema.json",
"implementation.schema.json"
]
Loading
Loading