# mdw/1 wire profile

The encoding and signature domains for mdw/1 certificates, manifests, listings, and publication pointers are
compatibility requirements for previously published data. Incompatible changes to these records require a new
version and a migration path. Optional discovery and administration extensions evolve separately. The
implementation and interoperability tests live in `crates/xan-proto`. See `docs/architecture.md` §3–§6.

The [mdw/1 test vectors](fixtures/wire-v1.json) give deterministic Ed25519 keys and exact CBOR bytes
for a publication certificate, its first manifest, and its public listing. The manifest's `index.md`
is empty and the title uses UTF-8. The fixture seeds are public test values. The Rust gate verifies
the bytes and reproduces them byte for byte when signing again. The pointer TXT vector is checked in
`crates/xan-proto/src/pointer.rs`.

## 1. Keys and ids

- Ed25519 everywhere. Three roles: the **person** key (identity root), one **publication** key per
  publication, one **device** key per device.
- A key's id is its 32 public-key bytes in **z-base-32** (most significant bit first, final character
  zero-padded): exactly 52 lowercase characters from `ybndrfg8ejkmcpqxot1uwisza345h769`. Only that
  canonical text parses (no uppercase, no non-zero padding bits). It is the same text Pkarr uses, so
  `mdw://<publication id>/path` names the key whose Pkarr record holds the pointer.
- Public keys are rejected unless they decode as Ed25519 points; signatures are checked with
  `verify_strict` (no small-order keys, canonical `S`).
- **Signature contexts.** Every signature covers `context ‖ 0x00 ‖ message`. Contexts (ASCII, no NUL):
  `mdw/1 manifest`, `mdw/1 certificate`, `mdw/1 listing` (`specs/director/README.md` §2). A signature for
  one kind never verifies as another.
- Seeds live in a key store supplied by the host (OS keystore). Names: `person`, `device`,
  `publication/<id>`. The core never writes a seed to an unprotected file.

## 2. Deterministic CBOR profile

RFC 8949 §4.2.1 core deterministic encoding, restricted to: unsigned integers (major 0), negative
integers (major 1), byte strings, text strings, arrays, maps **with text keys only**, `false`, `true`,
`null`. A decoder refuses:

- floats, tags, `undefined`, every other simple value, reserved additional information;
- indefinite lengths;
- any integer or length not in its shortest form;
- map keys not in strictly ascending bytewise order of their encodings (this also refuses repeats);
- invalid UTF-8 in text or keys; trailing bytes after the single top-level value;
- declared lengths longer than the remaining input, and limits on nesting, total values and string size,
  all checked before allocating.

Every allowed value has exactly one encoding, so decode-then-encode reproduces the input. Unknown map keys
are refused in every mdw/1 object in this draft (no silent extensions; a later draft will name an
extension field).

## 3. Certificate

```
{ "person": bstr(32), "subject": bstr(32), "role": "publication" | "device",
  "scope": null, "valid_from": tstr, "sig": bstr(64) }
```

`sig` = person key over the deterministic encoding of the same map **without** `sig`, context
`mdw/1 certificate`. `valid_from` is RFC 3339 UTC to the second (`2026-11-20T12:00:00Z`; other forms are
refused). `scope` is reserved and must be `null`. Rotation, revocation and expiry are not in this draft
(architecture §3: define before freeze).

## 4. Manifest

Envelope (what is stored, served and hashed):

```
{ "manifest": bstr(body), "sig": bstr(64) }
```

`sig` = publication key over the `body` bytes, context `mdw/1 manifest`. **Manifest hash** =
`blake3:` + hex of BLAKE3 over the whole envelope. `body` is the deterministic encoding of:

```
{ "protocol": "mdw/1",
  "publication": bstr(32),            publication public key
  "root_cert": certificate,           person → this publication key, role "publication"
  "title": tstr,                      ≤ 256 bytes, no control characters
  "seq": uint,                        ≥ 1
  "previous": bstr(32) | null,        null iff seq = 1; otherwise the previous manifest hash
  "updated": tstr,                    RFC 3339 UTC, seconds
  "access": "public",                 the only value defined in this draft
  "index": tstr | null,               must be one of files
  "feed": tstr | null,                must be one of files
  "files": { path: { "blake3": bstr(32), "size": uint } },
  "routes": { "https": [tstr], "nodes": [tstr] } }
```

Verification order: size ≤ 4 MiB → envelope decode → body decode → (optional) expected publication →
publication signature → certificate signature → rules (below).

Rules: ≤ 10 000 files, each ≤ 1 GiB; every path valid (§5) and no two colliding; `index`/`feed` listed in
`files`; ≤ 8 routes of each kind; HTTPS routes are `https://` bases ending in `/`, ≤ 512 bytes, without
whitespace, control characters, `,` `;` `"` `\`; node ids are 1–64 ASCII letters/digits (the network
layer defines their exact form); the certificate's subject is the publication key with role
`publication`.

Routes are hints. A reader fetches `<https base>.mdw/manifest` and `<https base><path>` and verifies
everything against the manifest; a route never vouches for content.

Writer rules (implemented by `Publisher`): `seq` increases by one per snapshot; publishing an unchanged
folder makes no new snapshot.

Removal signs a terminal head with an empty file map and no index or feed, before deleting the publication
key. The writer retains the signed manifest and a signed pointer packet, so it can advertise and serve the
proof when online. A reader that verifies this head reports the removal. Previously saved bytes may still exist
on independent devices, especially before they receive the terminal head.

## 5. Logical paths

`/`-separated, relative, NFC, ≤ 512 bytes, ≤ 32 segments, each segment 1–255 bytes. Refused: empty
segments, `.`/`..`, names starting with `.`, names ending in space or `.`, control characters,
`\ : * ? " < > |`, and Windows-reserved stems (`con`, `prn`, `aux`, `nul`, `com1`–`com9`,
`lpt1`–`lpt9`). Two paths **collide** when NFC + Unicode lowercase makes them equal; a manifest with a
collision is refused. Names read from disk are normalized to NFC first (macOS stores NFD).

Publishable files (folder snapshot): `.md`, `.markdown`, `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, and
`rss.xml`/`feed.xml`. No SVG (architecture §1b). Dot entries and symbolic links are skipped, so a publish
never reaches outside the chosen folder. Defaults: ≤ 10 000 files, ≤ 64 MiB each, ≤ 1 GiB in total.
`index` is the first of `index.md`, `README.md`, `readme.md`, `index.markdown` present.

## 5a. Opening an address

`mdw://<publication>/<path>`: `path` is percent-decoded, without the leading `/`. Readers resolve it
against the verified manifest, in this order:

- **The root** (`path` empty): the manifest's `index`; else the first of `index.md`, `README.md`,
  `readme.md`, `index.markdown` present; else, when the publication has exactly one Markdown file
  (`.md`/`.markdown`, any folder), that file; else the root's contents page.
- **`p`** (no trailing `/`): the file `p`; else `p.md`; else `p/<index name>` (same list); else `p`'s
  contents page.
- **`p/`**: `p/<index name>`; else `p`'s contents page.
- A contents page exists only for a folder with at least one Markdown file somewhere below it; otherwise
  the address is not found. Any folder is publishable as it is: no index file is required.

**Contents page.** Deterministic Markdown that every reader makes the same way from the signed version. It
is not a file of the publication and is never signed itself; its trust is the manifest's (the list it shows
is exactly the signed one), and readers mark it as made by the reader (Markmallow: `About.listing`).

```
# <title>                      the publication's title at the root, else the folder's last segment

[<site>](<../../>) / [<folder>](<../>) / <this folder>
                               below the root only: the way back up. The publication's title, then each
                               folder above this one, each a link; this folder's name last, as text

## Folders

- [<folder>/](<./<folder>/>) · <n> pages
                               one per child folder with a Markdown file somewhere below it; n counts
                               those files at any depth ("1 page")

## Pages

- [<title>](<./<file>>)        one per Markdown file directly in the folder
```

- A heading is written only when its group has an item. Folders first, then files; each group ordered by
  ASCII-lowercased name, then by the name's bytes.
- A page's `<title>` is the one the version's table of contents gives it (`toc.opml` at the root, §9a: the
  outline whose `url` is that page), when the version holds one and the reader has it. Otherwise it is the
  file's name without its last extension. A reader fetches that one file, verified by the manifest like any
  other, before it makes the page; when it can't, the names are shown.
- In titles and link text every ASCII punctuation character is backslash-escaped, so names are text.
- Link destinations are relative, start with `./`, are written in angle brackets, and have each segment
  percent-encoded (controls, space, `"` `#` `%` `<` `>` `?` `` ` `` `{` `}`).
- The page's base address is the folder's address with a trailing `/` (`mdw://<publication>/` at the root),
  so its links open inside the publication. Non-Markdown files are not listed.

**Directory lists in authored pages.** A writer can insert ordinary relative Markdown links to
the visible pages of a folder. With live updates enabled, the writer encloses those links between
`<!-- markmallow-directory flat . -->` and `<!-- /markmallow-directory -->`. The final argument
is the folder relative to the containing page, with each path segment percent-encoded. `flat` and
`tree` use page titles, with `tree` including subfolders. `flat-files` and `tree-files` use the
file name without its extension. Ordinary Markdown readers display the authored links.

A Markmallow reader refreshes membership from the same verified version. It excludes the containing
page, index pages, and names beginning with a dot or underscore. For a title-based list the reader
uses the version’s verified table of contents, then the authored label for that path, then its file
name. A reader can fetch the one table of contents for the page. Rendering a list never requires
downloading every linked page. Refreshing the display preserves the signed source bytes.

**Notes shown in place.** A reader may show a Markdown file of a version inside another page of the same
version. The author's page says where with a paragraph that holds only `![[path]]` (or `![[path|title]]`).
This is a convention between authors and readers: the manifest and the signatures know nothing of it, and a
reader that does not follow it shows the line as text.

- `path` is a relative reference, read as a link's destination is: resolved from the page's logical path,
  percent escapes decoded once. A name with no extension means `.md`.
- A reader resolves it in the verified version it opened the page from, and nowhere else: never another
  publication, never another version, never the web. A saved copy shows the notes saved with it.
- A reader bounds what it shows (the reference reader: 16 notes a page, 3 levels, 512 KiB of note source)
  and shows a link instead of a note that is missing, not Markdown, outside the publication, past a bound,
  or already open around the embed.
- The embedded file stays an ordinary page of the publication with its own address.

**Posts view.** `mdw://<publication>/?view=posts` (the root with `view=posts` in its query; other pairs are
ignored) is the whole publication as one flat list. Like the contents page it is made by the reader from the
verified manifest, deterministically, and never signed itself.

```
# <title>                                    the publication's title

- [<label>](<mdw://<publication>/<path>>)    one per Markdown post at any depth; label = its path without
                                             its last extension (a leaf index uses its containing folder)
```

- Ordered by ASCII-lowercased path, then by the path's bytes. No folders and no non-Markdown files.
- An `index.md` (ASCII case-insensitive) is a landing page and omitted unless it is the only immediate
  content file in its folder. Count all immediate files, including images and text; descendant folders do
  not count. Root protocol `follows.json`, `private.json`, and managed `mdw-replies/` output are excluded
  from this count, and so are the site's feed and table of contents at the root (`rss.xml`, `feed.xml`,
  `toc.opml`, §9a). Nested user files with any of these names are ordinary files.
- Explicit page and root URLs still open landing indexes. This changes automatic post lists only.
- Labels are escaped as titles are. Link destinations are the files' canonical addresses, in angle brackets,
  each segment percent-encoded as above.
- The version is the one the root would open. A list is made only from a whole verified manifest, never from a
  single page's saved copy.
- A private version (§17) has no posts view, and neither does a version without Markdown files: not found.
- Its address keeps `?view=posts`, so history and Back reopen the list. Any other path ignores `view=posts`.

## 6. Pointer record (Pkarr)

Name `_mdw`, one TXT value:

```
v=1;seq=<uint>;m=blake3:<hex>[;h=<https base>,…][;n=<node id>,…]
```

`v=1` first; `seq` ≥ 1 and `m` required; `h`/`n` follow the manifest's route rules; unknown keys are
ignored (later hints); a repeated key is refused. The text is at most **800 bytes**: BEP 44 caps the whole
value at 1000 bytes and the DNS packet (header, name, TTL, framing, 255-byte TXT string splits) needs the
rest. The record shows the key holder wrote it; it does not prove freshness, and the manifest it names is
verified on its own.

## 7. Heads

Per publication, durable `(seq, manifest hash)`. A higher `seq` advances; the same hash is a no-op; a
lower `seq` is refused as latest (still readable when pinned); the same `seq` with a different hash is a
**fork**: both are kept, the publication is flagged, and nothing advances automatically until reconciled.

## 8. Blob store

`blobs/<first 2 hex>/<64 hex>`, named by BLAKE3 of the content, written temp → fsync → rename. Every read
re-hashes; a mismatch moves the copy to `quarantine/` and reports it. Signed manifests are stored here
too (their hash is the BLAKE3 of their bytes).

## 9. HTTPS mirror layout

```
<base>/<path>                   each file at its logical path, bytes unchanged
<base>/.mdw/manifest            the signed manifest envelope
<base>/.mdw/manifest.json       the same manifest as JSON (people/debugging only; never verified)
<base>/.well-known/mdweb.json   {"k": "<publication id>"} (the HTTPS half of a domain alias, §3)
```

A plain browser, BonBon or Markdown Robot reads the Markdown unchanged. Export never writes through a
symbolic link and never deletes files a previous snapshot left. The version's `rss.xml` and `toc.opml` (§9a)
are files like the rest, so a mirror carries them at `<base>/rss.xml` and `<base>/toc.opml`. `bonbon.json`
generation is 0.4.

## 9a. The feed and the table of contents

A publisher puts two files beside the writer's own in every version it signs. They are made from exactly
the files that version holds, so they are never behind it. They are ordinary files of the version: listed in
the manifest, fetched and verified like any other.

**`rss.xml`**, at the root, named by the manifest's `feed`. RSS 2.0.

```
<rss version="2.0"><channel>
  <generator>Markmallow</generator>        first in the channel: the mark of a made feed
  <title>, <link>mdw://<publication>/</link>, <description>
  <item>
    <title>         the page's title as a reader gives it (front matter `title`, else the first heading,
                    else the path without its extension); plain text, at most 300 characters
    <link>, <guid isPermaLink="true">       mdw://<publication>/<path>, each segment percent-encoded
    <pubDate>       RFC 2822; left out when the post has no date
    <description>   front matter `description`, plain text, at most 400 characters; left out when none
```

- **Items:** the version's posts as the posts view lists them (§5a): Markdown files that are not landing
  indexes, and never a file under `mdw-replies/`. A file over 1 MiB is named by its path.
- **Dates:** front matter `pubDate`; else the date the feed of the version before gave that path; else, for a
  path the version before did not hold, this version's `updated`; else none. An edit keeps a post's date.
- **Order and bound:** newest first, the undated last, by path within the same time. At most 500 items.
- **Deterministic:** no build date. The same files, title and earlier feed make the same bytes, so a
  publish that changes nothing signs nothing.
- **The writer's own feed wins.** A version whose folder has `rss.xml` without the mark, or `feed.xml`,
  gets no made feed. One made earlier is dropped, so `feed` names the writer's.

**`toc.opml`**, at the root. OPML 2.0. `<head><title>` is the publication's title. Every Markdown file of the
version except those under `mdw-replies/`, in byte order of path, nested by folder:

```
<outline text="<folder name>">                              one per folder
  <outline text="<title>" type="link" url="mdw://<publication>/<path>" created="<RFC 2822>"/>
```

`text` is the page's own title, else its file name without the extension. `created` is front matter
`pubDate`, left out when there is none.

- A version with no Markdown file has neither file. A version at the file limit keeps the writer's files
  and leaves these out. Making them never stops a publish.
- **Reading.** A reader that follows a publication reads `feed`: its items that name a Markdown file of
  that version are the posts, each by its canonical address. A feed that names none of them (a writer's own
  feed that links to the site's web address) is no guide, and the reader lists the posts from the manifest
  as before. A version with no `feed` is read the same way. A reader fetches `feed` before the version's
  other files.
- **A feed may list Markdown web pages.** In any feed a reader takes (a web feed too), an entry's link may
  be `http`, `https` or `mdw://<publication>/…`.

## 10. Recovery file

An age v1 file (one scrypt passphrase recipient) holding one deterministic-CBOR map:
`format` = `xan-recovery/1`, `created`, `person` (seed), `publications` (id, title, created, seed,
certificate bytes, seq, head, updated, and the head's signed manifest so `previous` is known) and optional
reader `heads`. Device keys are never included. A restore:

- refuses to replace a **different** person key already on the device;
- checks every seed against its id, every certificate against the person key, every head against its
  signed manifest, before writing anything;
- never lowers a head; a different snapshot at the same `seq` is reported as a conflict and nothing is
  replaced;
- brings publications back as **writer elsewhere**: publishing is refused until the caller has resolved the
  current head from the network and called `take_over`, which only moves the head forward and refuses a
  same-`seq` fork.

## 11. Not in this draft

Private (`consensual`) manifests, Bao outboards and chunk-group verification, aliases and indexers fields,
certificate rotation/revocation, the four-word check, a paper
mnemonic, and known-device/endpoint bookmarks in the recovery file.

## 12. Peer protocol (0.2 draft)

Implemented by `crates/xan-peer`. A device serves the manifests and blobs it holds and fetches others'.

- **Transport.** iroh 1.x QUIC, ALPN `mdw/1`. A node id is the device key's id (§1): the same 52-character
  z-base-32 text as a publication id, so it fits a route's `nodes` entry and a pointer's `n=` list. The QUIC
  handshake proves the node holds that key and nothing more; content is trusted only by its hash or
  signature.
- **Streams.** One bidirectional stream per request. A requester keeps one connection per node and opens a
  stream for each request on it.
- **Request.** `kind (1 byte) ‖ key (32 bytes)`, then the requester finishes its send side.
  - `0x01` manifest: `key` is the publication's public key. The answer is the newest signed manifest
    envelope (§4) the node holds for it.
  - `0x02` blob: `key` is a BLAKE3 hash (§8). The answer is the blob.

  A serving node reads at most 64 bytes. Anything but exactly 33 bytes of a known kind (and, for a
  manifest, a key that decodes as an Ed25519 point) is answered `refused`.
- **Response.** `status (1 byte)`: `0` ok, `1` not found, `2` too large, `3` refused. Only `ok` is followed by
  `length (u64, big-endian) ‖ length bytes`, after which the stream ends. Any other status ends the stream
  after the byte. A requester treats an unknown status, a short body or extra bytes as bad data.
- **Limits.**
  - Size: a manifest is at most 4 MiB (§4). A blob is limited by the serving node and by the requester;
    both default to 16 MiB. The requester checks the announced length against its own limit before
    reading any of the body, and stops the stream when it is over.
  - Time: a request gets 20 s on each side, from connecting to the last byte. A server resets the stream
    when that runs out.
  - Load: a server answers at most 32 requests at once across all connections. Further requests are
    refused at once, not queued.
  - Not serving: a node whose owner turned serving off answers manifest, saved-manifest, blob and search
    requests `refused`, and still answers listings and director requests (`specs/app-api/README.md` §33).
- **Verification is the requester's.** A manifest must verify (§4) as signed by the publication key that was
  asked for. A blob must hash to the hash asked for. A failure is bad data; the bytes are never returned. A
  node is a source of bytes, never of trust; serving nodes answer from stores that verify on read (§8).
- **Not in 0.2.** Listings, pushes, ranges, chunk verification (§11) and any request beyond these two kinds.

**Reachability (interim default, flagged for review before 1.0).** The default endpoint uses iroh's n0
preset:

- relays at `{use1-1,usw1-1,euc1-1,aps1-1}.relay.n0.iroh.link`, which carry traffic when no direct path
  works;
- the device's addresses published to and looked up at `dns.iroh.link`, as Pkarr-signed node records;
- router port mapping (UPnP, NAT-PMP, PCP).

These are services run by n0. They see node ids and IP addresses, never content: the QUIC session is
end-to-end. The `Disabled` choice uses no relay, no lookup service and no port mapping. It dials only
addresses the app was given: a pointer's hints, a LAN listing, or a test. Self-hosted relays, or an opt-out
of n0, are open decisions.

## 13. Pointer publication

The §6 record is carried in a **Pkarr signed packet** under the publication key:

- one TXT record named `_mdw`, TTL **300 s**;
- the text is split into DNS character strings of at most 255 bytes, and readers join them in order;
- the packet is signed with the publication seed.

The Pkarr key text equals the publication id (§1).

- **Paths.**
  - The **Mainline DHT** (BEP 44 mutable item, via Pkarr), joined through Mainline's usual bootstrap
    nodes: `router.bittorrent.com`, `dht.transmissionbt.com`, `dht.libtorrent.org` and `relay.pkarr.org`.
  - **Pkarr relays**: by default `https://pkarr.pubky.app` and `https://pkarr.pubky.org`. A relay takes
    `PUT <relay>/<publication id>` with the packet's relay payload as the body, and answers
    `GET <relay>/<publication id>` with that payload, or 404.

  Every path gets its own 20 s. A slow path never decides the outcome for the others.
- **Publish** signs one packet and puts it on every path at once. It succeeds when at least one path
  stored it. When every path fails, the error lists each path's reason.
- **Resolve** asks every path at once:
  - Every packet must verify against the publication key (Pkarr checks the signature and the key's
    binding). A relay payload that fails is a failed answer from that relay.
  - From the verified packets, the `_mdw` records that parse (§6) are compared, and the highest `seq`
    wins. Equal `seq` falls back to the packet timestamp.
  - When no path has a record, the answer is "none" rather than an error. An error comes only when no
    path answered at all.
  - The DHT path may answer from its cache while the cached packet is younger than its TTL.
- **TLS.** One rustls provider (ring) for the whole app. Pkarr's own relay client is not used because it
  compiles aws-lc-rs; the relay protocol above is a PUT and a GET over the app's HTTP client.

## 14. Search request (0.7 draft)

A third request kind on the §12 stream: **`0x03` search**. A device answers it from its **public
projection** only: its own current publications and the publications it follows and keeps in full. Never
drafts, private publications, reading history, or pages it merely read. Answering is not a claim of
authority: every field in an answer is the answering device's claim until the reader opens the file and
verifies it against the publication key (§4).

- **Request:** `0x03`, then `limit` (one byte, 1–20), then the query as UTF-8 (1–256 bytes). So the longest
  request is 258 bytes (the §12 request cap). Anything else is answered `refused`.
- **Response:** the §12 OK framing (status 0, u64 length), then a CBOR array (§2 encoding) of at most
  `limit` maps, at most 256 KiB in all. Each map:

  | Key | Type | Meaning |
  |---|---|---|
  | `publication` | bytes (32) | the publication key |
  | `version` | uint | the manifest `seq` the answer was taken from |
  | `path` | text (≤ 1 KiB) | the file's logical path in that version |
  | `file` | bytes (32) | the file's BLAKE3 hash in that version |
  | `publicationTitle` | text (≤ 512 B) | the publication's title in that version |
  | `title` | text (≤ 512 B) | the page title (front matter `title`, else its first `# ` heading, else the file name) |
  | `snippet` | text (≤ 1 KiB) | plain text around the first match |
  | `score` | uint (0–1000) | the answering device's own match measure |

  Readers ignore unknown keys and refuse an answer over any bound. Answers are best first.
- **Matching (Markmallow's measure; a responder may use another):** the query's words (letters and digits,
  lowercased, at most 16) must each start a word of the page title, the publication title or the text.
  Points per word: 4 for the title, 2 for the publication title, plus up to 4 for occurrences in the text;
  `score = points × 1000 / (10 × words)`, capped at 1000. Bounded work: 256 KiB of text per file, 8 MiB and
  2,000 Markdown files per publication.
- **Privacy:** responders never log or keep the query text. Readers send a query only to devices of
  publications they follow, publications those recommend (§15), publications a director the reader chose
  listed under the query's words (`specs/director/README.md` §5), publications a signed listing passed on
  under those words led to (§14a), and devices that answered before.
- **Reader rules (Markmallow):** the network part of a search ends within 12 s with whatever arrived. Inside it,
  device asks (at most 32 devices, 8 at once, 5 s each), pointer lookups (at most 48, 8 at once, 6 s each;
  one that finds nothing frees its place for the next) and director lookups all run at once. Devices of
  followed publications are asked first. Publications to reach are then taken in turn from each source
  (recommendations of followed publications, listings passed on (§14a), then each director), so no source
  can crowd out the rest.
  Circles come only from verified bytes: 1 = followed, 2 = recommended in a followed publication's signed
  `follows.json`; everything else (a director's lead, a device that answered before) is outside. Rank on
  the reader: `score × weight`, weights own and followed 1.0, recommended 0.6, anything else 0.1. A device
  that answered for a publication is kept for 6 h as a route to it (tried after the pointer's and
  manifest's devices), so a page found through a keeper opens from the keeper when its publisher is
  unreachable.

## 14a. Listings request (0.14 draft)

A fourth, optional request kind: **`0x04` listings**. It carries the publishers' own signed listings
(`specs/director/README.md` §2, context `mdw/1 listing`) from device to device, so a publication listed
under some words can be found without any director. A listing is passed on exactly as signed: never
re-signed, never extended past its own `expires`. A device that passes one on can only withhold it or
replay it until it expires; the newest `issued` wins, so a replay can't undo a newer listing or withdrawal.

- **Request:** `0x04`, then `limit` (one byte, 1–16), then the query as UTF-8 (1–256 bytes), as §14.
  Anything else is `refused`. A device that predates this kind refuses it (§12); a reader treats any error
  from it as "passed none on" and never counts it against the device's search answer.
- **Response:** the §12 OK framing, then a CBOR array of at most `limit` byte strings, each one signed
  listing envelope of at most 16 KiB, at most 256 KiB in all; or `not found` when it has none. Readers
  refuse an answer over any bound and check every entry: it must verify completely (signature, encoding,
  bounds), not have expired, not be issued more than 10 minutes ahead of the reader's clock, and live at
  most 7 days. An entry that fails is skipped; the rest still count.
- **What a device hands over:** its own listed publications' current listings, whenever they are listed
  (the publisher's choice to be listed covers it), and only when its owner turns that on (Markmallow: Settings ›
  Pass on listings, off by default) the listings it kept from other devices. Never a publication's listing
  that its publisher didn't sign. A **withdrawal** carries no words: a device hands it over for the words of
  the listing it replaced (or its title's), until it expires. Answers rank by words matched, then newest.
  Matching is the director's (§5 there): a query word matches a listing word it starts.
- **Rate:** a device answers at most 60 listings requests a minute from one asking device and refuses the
  rest.
- **Reader rules (Markmallow):** inside the §14 envelope (12 s, 32 devices), the first 8 devices asked are also
  asked for listings, each for at most 16, 5 s each. At most 1 MiB of listings is read and 128 verified per
  search, whatever devices send. An active listing must also match the query's words; a withdrawal matches
  by publication. Per publication the newest `issued` wins and a withdrawal wins a tie with a listing issued
  at the same second. An accepted listing is one more source of publications to reach (§14 reader rules).
  An accepted withdrawal stops that publication's pending leads, and removes results that only a listing for
  it (a director's lead or one passed on) or the reader's search memory led to; results a follow or a
  recommendation led to stay.
- **What a reader keeps:** every withdrawal it accepted, for ordering, until 7 days after it was issued (by
  then any older listing has expired); its bytes are handed over only until they expire. A listing to pass
  on, only when the owner turned passing on on, and only when a device named by the publication's own
  signed pointer or manifest offered a result for it in that search. That ties the listing to a route its
  publisher authorized, and it's still not proof the page holds the words: the page is verified when it is
  opened (§4). Kept listings are bounded (Markmallow: 2,000 and 8 MiB, the soonest to lapse going first) and are a
  cache the reader can clear (Settings › caches: Listings passed on).

## 14b. Submit request and hosted directors (0.18 draft)

A device may **host a director** (`specs/open-network/PLAN.md` §2): the directory of
`specs/director/README.md`, on the device network instead of HTTP. Markmallow hosts one on a desktop with Help the
open network on, and `xan node` runs one headless; phones never do. A hosted director is addressed
**`mdw-node:<device id>`** (the z-base-32 node id), wherever a director's HTTPS address is accepted.

- **Listings:** a hosted director answers the §14a listings request from what it holds, after the device's
  own listings and any it passes on, within the same bounds. The reader rules of §14a apply unchanged.
  Readers ask a hosted director they were given like an HTTP one: inside the 12 s search, 4 s each.
- **Submit:** a fifth, optional request kind, **`0x05` submit**: the kind byte, then exactly one signed
  listing envelope (1 byte to 16 KiB). Anything else is `refused`. A device that hosts no director answers
  `not found`; one that predates the kind refuses it. The response is the §12 OK framing with exactly one
  byte: `0` listed, `1` withdrawn, `2` invalid, `3` stale (it holds one issued at the same second or later),
  `4` too soon (renewed under a minute ago), `5` expired, `6` full. Any other answer is bad data. A
  withdrawal issued in the same second as the listing it holds is not stale: it replaces it, as in §14a.
- **What it takes:** what an HTTP director takes (§3 there): verified listings and withdrawals, newest
  `issued` wins, within its capacity. A device also refuses (`invalid`) a listing for a publication it holds
  a private version of (§17).
- **Rate:** listings and submit requests share one budget: 60 a minute from one asking device.
- **Privacy:** like an HTTP director, it keeps no record of who asked or of a query's words. It holds
  publishers' own signed bytes, never re-signed, and saves them so they survive a restart.
- **A publisher** sends to a hosted director exactly as to an HTTP one (renewed every 6 hours and on each
  new version; a withdrawal once). `stale` counts as delivered: the director already holds that listing or
  a newer one.

## 15. Recommendations (`follows.json`, 0.7 draft)

A publication recommends others with a generated file at the root of its snapshot, **`follows.json`**,
signed like every file (it is in the manifest). It is made by the publishing app from the publisher's
explicit list and never written into the publisher's folder; a folder's own `follows.json` is not
publishable (§5), so the name can't collide.

```json
{"version":1,"follows":[{"address":"mdw://<publication id>/","title":"Fish Notes"}]}
```

- `version` 1. Readers refuse a file with another version, over 128 KiB, or over 500 entries.
- `address`: `mdw://<id>/` (a path after the id is ignored). Entries that don't name a publication are
  skipped; a publication listed twice counts once (the first). `title` is the recommender's label: one line,
  at most 200 characters, a hint only.
- Order is the publisher's. The file proves "publication A recommends B" from A's verified manifest; it
  proves nothing about B.

## 16. Web pages in search: a director's index of Markdown sites (0.39 draft)

A search also finds web pages written in Markdown that the reader has never opened. A director may keep an
index of web sites that serve Markdown and answer searches from it (`specs/open-network/PLAN.md` §7). What it
answers is a claim. The page is unsigned, and the reader fetches nothing from its site until the page is
opened. Rows from the reader's own library (app-api §20, API 0.15) are unchanged.

**The index.**

- **Who keeps one:** a director whose operator turned it on. On the command line, `xan director --web-seeds
  FILE` and `xan node --web-seeds FILE`. In Markmallow, Settings › Index Markdown sites (app-api §55): off by
  default, on a desktop only. A phone never keeps one. A private director (§21) never answers from one.
- **What it reads:** only the sites on its own list. A site is `https://host/` or a folder under it, with no
  user, query or fragment. A search never adds a site, and neither does another director or anything the
  operator reads.
- **A site's pages:** the site's own page, the pages its table of contents and feed list (§9a: `toc.opml`,
  `rss.xml`, `feed.xml`), and the same-site links of those pages, three links deep. Only addresses under
  the site's folder with no query. Only Markdown: an answer that is an HTML page is left out, whatever its
  address or content type says. At most 200 pages a site.
- **What is kept for a page:** its address, title, headings, the first 8 KiB of its text for matching, and
  the first 600 characters to show. Nothing about who searched, or for what.
- **The words are the ones a reader sees.** Front matter is not text. A page macro (`{{page.title}}`, as
  BonBon and markdownWeb pages write) is filled in from the page's front matter. A heading that repeats the
  title is not kept twice. The address inside a link or an image is left out: `[words](address)` keeps
  `words`. The same holds for the words of a signed page in search.
- **A site with no Markdown** is `refused`, and so is one whose `robots.txt` says no. A refused site keeps
  no pages and is tried again after a week. A site that could not be read keeps the pages of its last good
  read and is tried again after an hour. A site that was read is read again after a day.

**Polite reading.**

- **Name:** `Markmallow-Director/<version>`, with `(+<address>)` after it when the operator gave a page
  about the director (`--web-info`).
- **robots.txt** (RFC 9309) is read before every read of a site. The groups that name `Markmallow-Director`
  count; with none, the groups for `*`. The longest matching rule decides and an allow wins a tie. A site
  with no `robots.txt` (any 4xx) restricts nothing. One that cannot say (5xx, or no answer) is not read.
- **Pace:** one request at a time, at least 1 second apart, or the site's `Crawl-delay` up to 30 seconds.
  The gap also holds between two listed sites. A `429` or `503` ends the read, and the site is tried later.
- **Redirects** are followed by the crawler itself, at most 5 for one address. Each target is checked
  before it is asked for: the site's origin on https, under the site's folder, no query, allowed by
  `robots.txt`. A target that fails is never requested. Each hop waits its turn and counts as a request.
  A `robots.txt` that redirects is followed anywhere on the site's origin, and nowhere else.
- **Nothing is asked twice.** A `406` is the answer: the request is not repeated with another `Accept`.
- **`Content-Location`:** when the answer for a folder address names a file, the page is kept under that
  name, and only when that address passes the same checks. Otherwise the answer is not used.
- **Bounds:** public addresses only. A read takes at most 400 requests after `robots.txt`, 64 MiB and
  15 minutes.
- **The list decides what is kept.** What a read brings is written only while the entry that was read is
  still on the list. A site removed during its read keeps nothing. One removed and added again is a new
  entry: the read in flight writes nothing to it, and it is read afresh at its own turn.
- **Only the background reader fetches.** No search starts a read.

**Asking an HTTPS director: `GET v1/web?q=<words>&limit=<1–20>`** (`specs/director/README.md` §4 holds the
other requests).

- **Answer:** `{"api": 1, "pages": [{"url", "site", "siteTitle", "title", "snippet", "fetched"}]}`, best
  first. `fetched` is Unix seconds. Words match as a listing's do: a query word matches a page word it
  starts, and any of the words is enough. A word in the title counts most, then one in a heading.
- **A director that keeps no index** answers `404 notFound`. One that does also says so in `GET v1`:
  `"web": {"sites": n, "pages": n}`.
- **Rate:** the lookup limits apply (120 a minute from one address).

**Asking a device that hosts a director: request kind `0x15` web** (§12 framing).

- **Request:** `0x15`, then `limit` (one byte, 1–20), then the query as UTF-8 (1–256 bytes), as §14.
- **Response:** the §12 OK framing, then a CBOR array of at most `limit` maps with the text keys `url`,
  `site`, `siteTitle`, `title`, `snippet` and the unsigned integer `fetched`; at most 128 KiB in all. A page
  address is at most 2,048 bytes and a site address 512. Unknown keys are ignored. `not found` when the
  device hosts no open director or its director keeps no index. A device that predates this kind refuses it.
- **Rate:** as a listings request (§14a).

**Reader rules (Markmallow).**

- **Who is asked:** the directors a search already asks (the reader's own, and those found in the meeting
  place, §18), inside the same wait. A director that answers `not found` or refuses is not asked for web
  pages again for an hour. A private director is never asked for them. With no device network (Web only),
  no director is asked.
- **Scope (app-api §55):** a search for signed pages asks no index. A search for web pages asks no device
  for its pages, only directors. A search of this device asks no one.
- **Every row is checked:** the page address must be `https` with a host and no user, query or fragment,
  or the row is dropped. The site is kept only when it is a site address that holds the page; otherwise the
  page's origin stands in. Titles and text are cut to one line of bounded length, with control characters
  removed. At most 20 rows are taken from one director.
- **Whose row it is:** the row names the director this device asked, by the reader's own label for it. An
  answer cannot name another director.
- **One row an address:** the reader's own library row wins over a director's row for the same address.
  Of two directors' rows for one address, the first to arrive stays.
- **Rank:** by the reader's own measure and circle weights (§14), never by the director's order. A row is
  in the following circle only when the reader follows its site.
- **Nothing is remembered:** a web row a director found is not kept for the next search of the same words.
- **Opening a row** fetches the page through the normal path: reach checks, redirect limits, size limits,
  unsigned trust.

**Not in this draft.**

- A reader adding a site to someone else's director.
- Directors passing web rows to each other, and HTTPS mirrors of signed publications as web rows.
- A site proving it wants to be listed (`.well-known`), and devices answering from a shared list of sites
  without hosting a director.
- Sites that only convert HTML to Markdown on request, and outside search services.

## 17. Private publications (`private.json`, 0.17 draft)

A publication asks not to be found with a generated file at the root of its snapshot, **`private.json`**,
signed like every file. Like `follows.json` (§15) it is made by the publishing app, never written into the
publisher's folder, and a folder's own `private.json` is not publishable (§5), so the name can't collide.
A manifest field would have been refused by every reader of this draft (§2: unknown keys are refused); a
file is read by older readers as one more file.

```json
{"version":1,"private":true}
```

- **The marker is the path.** A version whose manifest holds `private.json` is private, whatever the file
  says, so a device decides from the verified manifest alone, without fetching the file. The body is for
  people and other implementations; readers don't need to fetch it.
- **A device that holds a private version** (its own, or a kept copy of one it follows) never answers a
  search (§14) with it. It never sends a listing for it (§14a, directors). It never passes on its listing,
  and drops one it holds. A director refuses a listing for a publication whose newest version it knows is
  private.
- **A private publication is unfindable, not secret.** Anyone given its address can still open it, and its
  pages are signed public files carried over encrypted connections. Devices that don't follow this draft
  can still index a copy they hold; the marker is a request every Markmallow honours, not access control.
- Turning privacy on signs a new version that adds the file, and Markmallow withdraws the publication's listings
  (§14a). Turning it off signs a version without it. A device holding an older copy treats it as private
  until it has the newer version, so a change can only make the publication harder to find, never easier.

## 18. Meeting place (0.19 draft, `specs/open-network/PLAN.md` §3)

Where always-on devices list themselves, so a device that knows nobody finds them. It lives on the Mainline
DHT (and the pkarr relays) as ordinary pkarr packets, like pointers (§6), so a phone that can't reach the
DHT still reads it through a relay.

- **Slots.** For each UTC hour `H = floor(unix / 3600)` there are 16 slots, `s = 0..15`. Slot `(H, s)` is
  the pkarr packet of the Ed25519 key whose seed is BLAKE3 `derive_key("mdw/1 meeting place", u64be(H) ||
  u8(s))`. Anyone can compute that key and write the slot: there is no sign-up and no owner. That is why
  every entry is signed by its own device, and why readers never trust a slot's contents beyond that.
- **Entry.** One TXT record at `_mdw-meet` (TTL 300) per device:
  `v=1;n=<device id>;r=<roles>;e=<expiry>;s=<signature>`. `n` is the device's node id (z-base-32, §12);
  `r` is its roles, today `d` (hosts a director, §14b); `e` is unix seconds; `s` is unpadded base64url of
  the device key's Ed25519 signature over `mdw/1 meeting entry` || 0x00 || node id (32 bytes) || roles
  (UTF-8) || 0x00 || u64be(expiry). Readers skip an entry that doesn't parse or verify, has expired, or
  expires more than 35 minutes ahead. A packet holds at most 5 entries (pkarr's 1,000-byte limit).
- **Joining and renewing.** A device writes its entry with a 30-minute expiry into slot
  `BLAKE3(node id || u64be(H))[0] mod 16` of the current hour, and in the last 10 minutes of an hour into
  that hour's and the next hour's slots. It renews every 10 minutes. Because the slot depends on the hour, a
  full or vandalized slot is a different slot an hour later.
- **Writing a slot.** Read the slot over every path, merge the valid entries of every copy (per device the
  latest expiry), drop expired ones and the writer's own, add the writer's fresh entry, keep at most 5
  (dropping the soonest to expire), sign with the slot key and publish over every path. A write refused as
  older than a copy already seen is read and written again, at most twice.
- **Leaving.** Write the slot again without one's own entry (for each hour it wrote). A device that just
  vanishes ages out within 30 minutes.
- **Reading.** Read all 16 slots of the current and the previous hour over every path, at once, and take
  every valid entry, newest expiry per device. A reader keeps at most 64 per lookup. An entry is only a
  claim to be reached: the device-network connection proves the node key, and a director proves itself by
  answering. Markmallow keeps what it found for 10 minutes while it runs, and reads the place in the background,
  so a search rarely waits for it; a cold one waits at most 5 s, inside its 12 s.
- **Directors passing on directors.** A sixth, optional request kind, **`0x06` directors**: the kind byte
  alone (anything else is `refused`). A device that hosts a director answers with the §12 OK framing and a
  CBOR array of at most 64 device ids, each a 32-byte byte string (2,192 bytes at most): the directors that
  answered its own `directors` request in the last hour, most recent first. A device that hosts none
  answers `not found`; one that predates the kind refuses it. It shares the listings and submit rate budget
  (§14b). An answer means the device hosts a director; the ids it names are only claims.
  - **Always-on devices** ask every 10 minutes, when they renew their entry: up to 16 directors, from the
    meeting place, those that answered last time and those named since, 10 s each.
  - **Readers** ask too when the meeting place lists fewer than 6 directors: 2 of them (or of their saved
    ones), 3 s more at most.
  - **Saved directors.** Markmallow keeps each director that answered a search for a week (its search memory,
    cleared with Settings › caches › devices), so after a restart it starts from them.
- **Using what was found.** A publisher lists each searchable publication with the first 4 directors the
  meeting place lists, in device-id order; directors pulling from each other (§20) carry it on from there.
  A reader asks up to 6, after its own directors: those same first 4, then its saved directors, then the
  rest of the meeting place, then directors named by others. So a reader's six include a publisher's four.
- **Abuse.** A junk entry costs a reader one connection attempt, inside the per-search cap, and never
  produces a result. A slot overwritten with junk loses its real entries for at most an hour; other copies,
  directors passing on directors and saved directors cover the gap. A device that answers `directors` with
  junk ids costs the same, and only when the place is short. Device-id order can be gamed by minting ids
  that sort first; saved directors that answered come right after the first 4, and the publisher's own
  directors and the reader's own are always asked first. Ranking found directors by how well they answer
  comes with federation (`specs/open-network/PLAN.md` §4).

## 19. HTTP gateway (0.19 draft, `specs/open-network/PLAN.md` §7)

An always-on device can show searchable publications to plain web browsers, so a link to a page works for
someone without Markmallow. Markmallow: `xan node --gateway ADDR`, plain HTTP for a TLS proxy in front (nk.tools: a
`/mdw/` route).

- **Address.** `/mdw/<publication id>/<page>`; `/mdw/<id>` is the index. Paths that climb (`.` or `..`),
  carry a backslash or a control character, or name no valid key are refused (404). `/` and `/mdw/` say what
  the gateway is. GET and HEAD only (405 otherwise, `Allow: GET, HEAD`).
- **What it serves.** The page is opened exactly as a reader opens `mdw://<id>/<page>`: pointer, devices,
  verification. Only a page that finishes `Signed` by that publication is served. A private publication
  (§17), an unknown one, one that can't be reached in 20 s and one that doesn't verify all answer the same
  404, so the gateway never says that a private publication exists. It uses its own cache, never a reader's
  library.
- **The page.** A small HTML document: the publication's safe HTML from its block tree (app-api
  `RenderedDoc.html`: no markup from the page itself survives), a line saying it is signed and checked with
  an "Open in Markmallow" link to the `mdw://` address, and the publication id and version. Links: `mdw://` ones
  become gateway paths, anchors stay, web links get `rel="nofollow noopener noreferrer"`, mail links become
  `mailto:`, and links a reader never follows have no `href`. Images stay as their descriptions.
- **Headers.** `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; base-uri 'none';
  form-action 'none'; frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`, `Referrer-Policy:
  no-referrer`; pages `Cache-Control: public, max-age=60`, errors `no-store`.
- **Bounds.** 256 connections, 8 pages opening at once (503 with `Retry-After: 5` past that), 10 s for
  the request head, 60 s per connection.
- **Privacy.** Nothing about a request is logged or kept. The gateway fetches as any reader does, so the
  publisher's device sees the gateway's device, never the visitor.
- **Not yet:** images, other files, and an HTTPS mirror link in director answers (`specs/open-network/PLAN.md`
  §7, mdweb to HTTP).

## 20. Federation: directors pull from directors (0.20 draft, `specs/open-network/PLAN.md` §4)

Directors hosted on devices share what they hold, so a listing sent to a few of them reaches the others.
A director pulls; nothing is pushed.

- **Change numbers.** A director numbers each publication's latest change: a listing taken, or a
  withdrawal taken. A new change to the same publication gets a new, higher number, and the old one goes.
  The numbers belong to an **epoch**, a random non-zero u64 kept with the director's saved listings; a
  director made anew (or one saved before it kept numbers) has a new epoch.
- **Request:** a seventh, optional kind, **`0x07` changes**: the kind byte, `epoch` (u64be), `after`
  (u64be) and `limit` (one byte, 1–64), 18 bytes exactly. Anything else is `refused`. A puller that never
  pulled sends epoch 0.
- **Response:** the §12 OK framing, then a CBOR map: `epoch` (uint), `next` (uint), `more` (bool) and `items`
  (an array of at most `limit` byte strings). Each item is one signed listing or withdrawal exactly as its
  publisher signed it (§14a), at most 16 KiB, at most 256 KiB in all. Items are the changes after `after`,
  lowest number first: current listings, and withdrawals until they expire. When the request's epoch isn't
  the director's own, the answer starts from the director's first change and carries its epoch. `next` is
  the last change the answer covers (`after` when there are none); `more` says changes wait after it. A
  device that hosts no director, or only a private one, answers `not found`; one that predates the kind
  refuses it. It shares the listings and submit rate budget (§14b).
- **Pulling.** After each round of asking directors whom they know (§18, every 10 minutes), a director
  pulls from up to 8 directors that answered in the last hour: from each, up to 16 pages of 64, 10 s each,
  continuing from the epoch and `next` it kept for that director. It keeps those, with its listings, across
  restarts. Losing them only means pulling again.
- **What it takes.** Every item goes through exactly the checks of a submit (§14b): verified completely,
  newest `issued` wins, a withdrawal wins a tie with a listing issued in the same second, within capacity,
  and never a listing for a publication the device holds a private version of (§17). The one difference: the
  one-minute renewal limit (`too soon`) doesn't apply, since it limits how often a publisher sends, not how
  fast a listing travels. A director can withhold a listing; it can't forge, re-sign or extend one.
- **Bounds.** At most 4 MiB from one director per round. Relayed listings can occupy up to half the
  index. Each source can occupy up to one thirty-second of capacity, rounded up and capped at 1,024.
  These limits persist across restarts. Direct publishers can replace an earlier-expiring listing
  when the index is full, with relayed listings displaced first.
- **Readers pull too (Markmallow's Home, Newly found, `specs/app-api/README.md` §28).** A device that hosts no
  director may send `changes` to directors it found in the meeting place: up to 4 at once, 8 pages in all, 2
  from each. It keeps each director's epoch and `next`, and refuses a page that doesn't move forward from
  them: under the same epoch, `next` below `after`, or not above it while the page carries items or `more`;
  under a new epoch, `next` 0 with items or `more`. It takes items with the checks above, shows a
  publication only once its signed pointer (§6) resolves, and never contacts the publisher's devices.
- **Not yet:** culled listings left out of answers (`specs/open-network/PLAN.md` §6).

## 21. Private directors (0.20 draft, `specs/open-network/PLAN.md` §4, O6)

A director can be private instead of federating: only people with its address can use it, and it holds only
listings sent by people who were given that address.

- **Address.** `mdw-node:<device id>?key=<key>`, the key being 32 random bytes in z-base-32 (52 characters),
  made when the director is first hosted and kept beside its listings. The address is a secret, as a
  password is: whoever has it can search and list there. A new key makes a new address, and the old one
  stops working.
- **Request:** an eighth, optional kind, **`0x08` keyed**: the kind byte, the 32-byte key, then a whole
  `listings` (§14a) or `submit` (§14b) request. Any other inner kind, a nested keyed request or a short key
  is `refused`. The answer is the inner request's answer. It shares the listings and submit rate budget.
- **Answering.** A device hosting a private director answers a keyed request only when the key matches,
  compared in constant time. To everything else (another key, an unkeyed `listings`, `submit`, `directors`
  or `changes`) it answers as a device that hosts no director: `not found`, or for `listings` only what it
  passes on as any device does (§14). So nothing tells a stranger that a private director is there.
- **What it takes.** A keyed submit gets every check of §14b, including the one-minute renewal limit and
  never a listing for a publication the device holds a private version of (§17).
- **Out of the open network.** It isn't in the meeting place (§18), names no directors and is never named,
  doesn't answer `changes` and doesn't pull (§20). A reader never saves it as a found director.
- **Using one.** It is added like any director, with the whole address (Settings › sources, or `xan
  --director`). A publisher sends its listing with the key; a reader asks with the key. The app never
  logs the address or shows the key in a label. Markmallow: `xan node --private` hosts one and prints its
  address once when it starts, for its operator, so a service journal holding that output is as secret
  as the address.

## 22. Open relays (0.20 draft, `specs/open-network/PLAN.md` §5)

An always-on device may run an iroh relay with a public TLS name. The relay passes the peers’ encrypted
QUIC traffic and sees their node IDs and network addresses. The peer connection authenticates the remote
device. Publications and file bytes retain their normal signature and hash checks.

- **Request `0x09`** is the kind byte alone. Under the normal response framing, its body is the relay URL
  as UTF-8 with at most 256 bytes. Only an HTTPS origin is valid. Credentials, query strings, fragments
  and paths other than `/` are refused. A device without an advertised relay answers `not found`.
- **Meeting place.** A node with role `r` can publish `v=2;n=<node>;r=<roles>;e=<expires>;s=<signature>;u=<url>`.
  The URL is the canonical HTTPS origin, without semicolons. The signature uses the v1 context and
  message from §18, with the UTF-8 URL appended after the big-endian expiry. The `r` role, the URL and
  the entry’s expiry are therefore signed together. A reader can discover the URL without dialing the
  operator. The `r` role in an older v1 entry requires the peer request. v1 readers skip v2 entries.
  If adding the URL makes the slot exceed the packet limit, the writer keeps its own entry first and
  drops the last entries until the packet fits.
- **Selection.** The app tries open relays if its default relays are unavailable. The CLI adds them
  alongside the defaults only with `--open-relays`. At most eight operators are considered in one
  round and at most four open relays are added. Public discovery checks candidate addresses and admits
  only origins that resolve to public IPs. The relay connection performs normal TLS validation.
- **Hosting.** `xan node --relay HOST` starts a relay alongside the director, with an operator certificate
  or Let's Encrypt. The relay limits each device’s sends to 2 MiB/s with an 8 MiB burst budget. A private
  director does not advertise an open relay.

## 23. Hosted director reachability (0.20 draft)

A desktop director tries to bind UDP 47160. The CLI `xan node --port N` can choose another fixed port.
A busy fixed port falls back to an automatically assigned UDP port, with relays available. A fixed-port
director asks its router for an automatic UDP mapping through UPnP, PCP or NAT-PMP, advertises any
mapping as an endpoint candidate, renews while hosting and requests release on orderly shutdown.

The local status reports the bound fixed port, the device address toward the router, the router’s reported
capabilities and the public address observed by a network probe or mapping. A mapping with evidence of
another outer IPv4 address is not reported as public. The reachability state is an inference from local
observations. No unsolicited internet dial-back request is used. A port forwarded manually on the router
can help when the fixed port is bound, subject to the upstream network and firewall.

## 24. Saved copies and provider discovery

A reader saves the exact Markdown bytes and the author’s verified manifest. Peers request the
original publication ID and validate its signature, then request the file by the BLAKE3 hash the
manifest names. Copies keep the original address and attribution. An ordinary browser cache does
not grant permission to serve a file. Removing a saved page stops serving its bytes immediately.
Private publications and unsigned web pages are excluded from public provider announcements.

A keeper advertises short-lived device locations separately from the author’s pointer. Each UTC hour
has four Pkarr slots derived by BLAKE3 derive-key in context `mdw/1 saved providers slot`. The input
is the 32-byte publication public key, the big-endian u64 Unix hour (Unix seconds divided by 3,600),
and the one-byte slot number (0–3). The keeper writes in the current hour. Readers check the current
and previous hour. The slot for a keeper is the first byte of the BLAKE3 hash of its device public key
modulo four.

The `_mdw-keep` TXT value is `v=1;<device-id>;<expires>;<signature>`, with a z-base-32 device ID,
decimal Unix seconds, and base64url without padding for the signature. The device signs the
publication key bytes followed by the big-endian u64 expiry in context `mdw/1 saved provider`.
A lease expires after an hour. Each slot preserves at most five leases and each lookup returns at
most eight devices. Writers merge live leases and renew while actively serving. Readers verify
a lease for the requested publication and treat it as a route hint. A keeper can provide an older
verified copy when the newest version cannot be fetched.

If the available manifest names a version of the file that no device can serve, a reader may ask
for the manifest kept with the page. The optional `0x0a` request is one kind byte, the 32-byte
publication key, and the decoded UTF-8 path with no leading slash or fragment. The root uses an
empty path. The path is bounded to 512 bytes plus an optional trailing slash. A keeper answers
with the usual manifest response for an explicitly saved page or `not found`. The reader still
verifies the original author signature and the requested file hash, and displays it as a kept copy.

## 25. Network-wide device names (phase 1: test and self-hosted registries)

A device name such as `jdb.system76.mdw` resolves to the Iroh endpoint serving it. The device
profile's hostname hint stays local until its owner registers the name. A name opens the device's
public post list (§25a). Each page still opens and shares at its own `mdw://<publication-key>/<path>`
address, verified by its author key. `crates/xan-names` implements this section.

### Registries

A registry is named by a bootstrap file. The reader imports the file (the app keeps it in its data
folder, and the CLI takes `--names-bootstrap FILE`). Without one there are no device names, and
nothing talks to a registry. The file is public and holds no secret. It is JSON (`format: 1`) with:

- `network`: the network id every signature covers;
- `kind` (`test` or `selfHosted`) and a `label`;
- `groupKey`, the FROST public key package and `threshold`;
- the sequencer and every signer, each with its pinned Iroh endpoint id and the direct addresses or
  relay it is reached on (as trusted as the pinned keys beside them);
- `relays` (`none`, `n0` or a list of URLs);
- `policy` and `dht` (`mainline`, or a closed test DHT's nodes).

A reader checks it whole before use. The checks cover the threshold against the key package, every
endpoint as a valid Ed25519 point, and relay URLs (https, with a host and no credentials).

- **Test** registries come from `xan names test-bootstrap`, a trusted dealer. Each share is written
  only into its signer's folder, and the dealer keeps no copy. They are reversible: stop the roles
  and delete the files, and every record lapses within 3 hours.
- **Self-hosted** registries are run by an operator the reader chose to trust.
- **Independent key-generation candidates** use the [operator DKG tools](DKG.md). The verified
  participant roster and resulting candidate do not automatically become a public trust anchor.
- **Public:** none exists. One needs a key ceremony (DKG) across independently operated machines and
  an owner decision on its operators, and none of that is in this phase.

An open director can explicitly advertise a chosen public bootstrap. Optional peer request
`0x10` is the kind byte alone. The response is at most 64 KiB of UTF-8 bootstrap JSON, or not
found if the director shares none. Readers can ask up to eight authenticated directors found
through the existing DHT meeting place. The director's identity authenticates the source of
the hint. Trust in the registry requires the reader to compare the group fingerprint and accept
it explicitly. Checking for hints sends no requests to the advertised registry. A private
director offers no hint. The headless node uses `--names-bootstrap FILE --advertise-name-registry`.
An operator can co-host the registry's sequencer in that node with `--registry-sequencer DIR`,
where DIR contains the configured sequencer's key and log. The registry still needs its signer
quorum.

### Ordering and signing

One operator-led **sequencer** orders requests into an append-only log. **Signers** each hold one
FROST Ed25519 share; the test registry has 3 signers with a threshold of 2. The sequencer holds no
share and can sign nothing alone. Every signer replays the same log and checks each entry before it
signs at that index. Each signer persists a guard naming the one history it signs. Without enough
signers a change stays committed but unsigned (pending), and nothing falls back to any single key.

This tolerates a crashed or restarted signer or sequencer under an honest sequencer and honest
signer processes. It is **not** Byzantine fault tolerant. A registry of independent public validators
needs consensus with finality certificates, as in [HotStuff](https://arxiv.org/abs/1803.05069).

Operations are signed by the owner key for one network: `Reserve(base, requestId)` with a proof of
work, and `Renew` or `Release` of an assignment named by its original log index. Each entry is
persisted and synced before anything reports it. The candidates for a base are the base, then
`1.<base>`, `2.<base>`, and so on. A committed reserve takes the first candidate free at that point in
the log, so simultaneous claims by different owners get the base and `1.base` in committed order.
Only the registry assigns a name whose first label is all digits.

Each decision also gets a group-signed receipt for exactly that owner, request and operation digest.
A retried request id returns its first decision. A client saves its signed operation before first
sending it and resends the same bytes until its receipt arrives. It reports a name confirmed only on a
verified receipt.

### Rules (no payments)

Lease 180 days from commit; renewing sets commit time + 180 days. Grace 30 days, during which only the
owner can renew and the name still resolves as renewal due. A reserve needs a proof of work of 22
leading zero bits (20 in test registries) over the network, owner, request, base and nonce, and an
owner holds at most 8 live names. The sequencer also throttles before committing: 6 submissions a
minute per endpoint, 120 a minute overall and at most 1,000 pending. Past that it answers busy and
remembers nothing.

### Records

A name's **registry record** is BEP44-salted mutable data under the group key.
- Salt: `blake3 derive_key("project-xan mdw name salt v1", network ‖ 0 ‖ name)`.
- Value: the domain `project-xan mdw name record v1\0`, then network, name, state (held, grace, released,
  free), owner, generation (the assignment's log index), lease end, grace or cooldown end, `asOf` (the log
  index it was signed at), log head, `signedAt` and `freshUntil` (= `signedAt` + 3 h).
- `seq` = `asOf`. It is durable and strictly increasing, so two changes in one second still order.

The group signs the BEP44 signable bytes themselves. An hourly tick in the log refreshes every live name's
record, and the sequencer republishes them every 45 minutes.

An assignment's **endpoint record** is BEP44-salted under the owner key.
- Salt: `blake3 derive_key("project-xan mdw endpoint salt v1", network ‖ 0 ‖ name ‖ 0 ‖ generation)`.
- Value: the domain `project-xan mdw endpoint record v1\0`, then network, name, generation, revision (=
  `seq`), issued, expires (issued + 3 h) and 0–4 endpoint ids, the first preferred.
- The device republishes it every 30 minutes while serving.
- A move is a higher revision listing the new endpoint. **Serve publications** off publishes a higher
  revision with no endpoints, a signed withdrawal. A record already in the DHT can't be deleted, but the
  withdrawal outranks it, and every record expires within 3 hours.
- The device saves the revision before signing. A result is kept only while its revision is still the
  latest, so two records never share a revision and an older one never overwrites a withdrawal.
- **Web only** sends nothing at all. The last record lapses on its own, and the device refuses to serve at once.

### Resolution

A reader asks the sequencer and the DHT at the same time, about 8 seconds each, and keeps the
verified record with the highest `asOf`. That includes its persisted cache, so it never goes backwards.
- It uses that record only while it is **valid**: before `freshUntil`, and for a held name before its
  grace ends.
- **No such name** is only ever a valid record saying free or released. An empty lookup or an unreachable
  registry is "couldn't confirm", never "not found".
- Then it takes the highest unexpired endpoint record for exactly that owner and generation. One the
  sequencer sends along needs no second lookup; otherwise one more 8-second DHT lookup. A resolve takes
  about 16 seconds at most.
- An endpoint record with no endpoints means the device isn't serving its name now.
- The reader authenticates the endpoint when it connects.

**The bounded tail.** A cut-off reader holding a valid record of a released name may still go to
the former owner's endpoint until that record's `freshUntil`, at most 3 hours after release. It never
goes to a different owner: a released name **cools down** for the same 3 hours. A different owner
asking for it meanwhile gets the next candidate. Natural expiry has the 30-day grace as its bound.

### Using it

- **App:** registration lives in Settings under the identity, and the person identity key owns the
  device's names (§35 of the app API). Registering needs an identity; browsing by name needs only a registry.
- **CLI:** `xan names test-bootstrap|sequencer|signer|register|renew|release|list|resolve`. `xan node
  --name` keeps a name's endpoint record listing the node and withdraws it on stop. `xan open` resolves
  names through `--names-bootstrap`. A CLI device's owner key is `DIR/names-owner.key`.
- **Acceptance** (`crates/xan-names/tests/federation.rs`) covers, on loopback Iroh and a closed Mainline
  test DHT:
  - concurrent claims by different owner keys;
  - one device's concurrent claims of one name;
  - retry after a lost answer and a restart;
  - quorum loss with no fallback, then recovery;
  - a sequencer restart;
  - a device move and concurrent publishes;
  - a withdrawal;
  - release, then cooldown against a different owner;
  - the stale replay tail;
  - cold readers starting from the name alone, with and without the registry.

### 25a. Open a device’s public posts

A reader opens a confirmed `.mdw` name or an `iroh://<endpoint-id>/` link at the device’s public
post list. Markmallow accepts `mdw-node:<endpoint-id>` and Iroh endpoint tickets in its address bar.
A bare name ending in `.mdw` goes to the MDW resolver. Ticket coordinates are bounded and
subject to public route checks. The canonical device link without a name is
`mdw://<endpoint-id>/?view=device`. An `mdw://<publication-key>/<path>` link still opens the
publication or page using its author key.

The optional MDW peer request `0x0b` consists of the kind byte alone. Its success payload is
canonical CBOR `[truncated: bool, pages: array]`, with up to 192 rows of
`[publication: bytes(32), path: text, publicationTitle: text]`. Each path is a valid logical path
ending in `.md` or `.markdown` and the title is limited to 200 UTF-8 bytes. The reply is
authenticated by the endpoint connection. The publication title is a hint until the reader opens
the page and verifies the author signature and the bytes.

Devices list the Markdown they currently serve, including pages explicitly saved for public
serving. Private versions, drafts and ordinary read-cache items are excluded. **Serve publications**
off refuses the request. An older endpoint may refuse it or answer `not found`. The resulting
list uses canonical author links regardless of how the reader reached the device.

**Classified catalog (optional `0x11`).** The request is the kind byte alone, with no body. Its reply
keeps `[truncated, pages]`, but each row is `[publication, path, publicationTitle, landing: bool]`.
The path, title, row count and total-byte bounds are the same as `0x0b`. The serving device derives
`landing` from the complete verified manifest for that exact hosted file's version, counting files as
§5a specifies once per manifest, before filtering to hosted Markdown. An uncached sibling asset still
counts. The authenticated endpoint's role is a claim; author signatures and content are verified on open.

The client tries `0x11` first and retries unchanged `0x0b` only after not-found or refusal (old clients
refuse unknown kinds). It never downgrades invalid/oversized replies, timeouts, or connection failures.
A provider without classified roles declines `0x11`. `0x0b` retains its exact bytes and all Markdown
pages, including indexes; its rows have unknown roles and must not nominate a homepage.

A v2 device list omits landing rows while retaining those rows for homepage selection. Only a complete,
single-publication catalog with a served root `index.md` identifies a homepage. A second publication
still counts even if all of its Markdown rows are landings. A truncated/legacy catalog, multiple
publications or missing root index falls back transparently to its list. A leaf root index may be both
a post and the homepage. No per-publication network fetch is needed to classify the catalog.

### 25b. One address per installation

New app registrations use `SetAddress`, signed by the installation's existing endpoint key.
The base is `domain.device.mdw` with two lowercase labels of up to 63 ASCII letters, digits or
non-terminal hyphens. A registry can prefix a decimal increment from 1 through 9999. It reports
exhaustion when all candidates are taken. A signed receipt identifies the exact assigned name
and device key. A numbered offer for a replacement requires confirmation.

A replacement commits the new assignment and a redirect from the former name in one entry.
A shared device link includes `?device=<endpoint-id>`. When the reverse record identifies a newer
name for that endpoint, the reader displays the updated address. When a registry cannot confirm
the alias, the pinned endpoint can still be opened by its stable key. The covered deployment is
a configured test or self-hosted registry.

### 25c. Independent registry join preview (read only)

`xan_names::join::preview_join` computes a bounded proposed reconciliation for **explicitly trusted**
test/self-hosted registries. It does not import a bootstrap, allocate a live name, publish a DHT
record, change a device key or alter either registry. `Client::address_join_evidence` reads the
saved device operation, its original group-signed `SetAddress` receipt and a currently valid
device-bound name record. The public JSON evidence contains those proofs in lowercase hex, plus
the source network and group-key identifiers; it contains no private keys. Evidence cannot grant
trust to its own source. The caller supplies and validates the trusted bootstrap files separately.

The verifier checks the owner signature, receipt signature and exact operation digest; the
receipt's assigned owner/name/generation; and the current signed record's matching endpoint key,
name and generation. Only successful `SetAddress` receipts participate. Legacy `Reserve` records,
released names, expired proofs, future clock/index inconsistencies and unknown registries fail
the whole preview. Renewing or refreshing a record never replaces its original receipt's
`registered_at`. A renamed address needs the receipt for the replacement registration; the first
ever use of an endpoint key does not reserve priority for every name it might later choose.

For each requested `domain.device` base, order unique devices by witnessed registration time,
then group key, network id, source assignment generation and device key as deterministic ties.
Assign the base to the first device, then increments `1` through `9999`. An endpoint registered
with the same base in multiple sources participates once, using its earliest verified witness,
and retains every source origin. If one endpoint currently claims different bases across sources,
refuse the preview until its owner chooses which address to retain. Input ordering and duplicate
evidence do not change the result. The limits are eight trusted registries, 4,096 evidence items,
16 KiB per JSON evidence file, and the existing per-proof byte limits.

Every proposed address retains its original endpoint key. The preview exposes the existing
`mdw://<old-name>/?device=<endpoint-id>` links, its proposed name with the same device pin, and the
stable `mdw://<endpoint-id>/?view=device` link. A collision does **not** authorize a bare old name
to redirect to two different devices. Endpoint-pinned links preserve identity even when an alias
cannot yet be confirmed; existing publication-key page links remain unchanged.

The result includes the checked signed source indices, heads and times, the earliest proof or
assignment expiry, and a deterministic evidence digest. Conflicting heads or times at one source
index are refused. A source's newer record supersedes an earlier still-valid record for the same
device. Repeated receipts/records are idempotent. A head is evidence of what those selected signers
signed, **not** proof of a complete, latest or atomic export; a record can remain valid during the
existing three-hour stale tail. Rebuild and review after any source changes or proof expiry.

Witnessed time means the selected source operators' committed clock, with the existing skew
bound. It is not objective global chronology. Unknown sources are refused before ordering. A
signature does not prove clock honesty: admitting a malicious trusted quorum would let it claim
an ancient registration time. FROST authenticates the source's
statement under the current honest-process/crash-only model; it supplies neither cross-registry
consensus nor Byzantine finality.

**Applying a join is not implemented.** It requires complete consistent source checkpoints, a
mutual freeze/handoff so neither registry keeps allocating divergent names, approval of the exact
merge digest by both source quorums, destination quorum/key-policy compatibility, durable replay
and idempotent recovery, and coordinated forward/reverse records while old proofs age out. A
preview digest is unsigned and grants no such authority. No public bootstrap, operator ceremony,
live registry mutation or production rollout is part of this slice.

The follow-up [stopped-role migration tools](MIGRATION.md) add complete checkpoint replay, durable
source freeze, exact source-quorum approval, fresh destination genesis import, destination-quorum
certification and explicit role activation. Native/CLI device adoption checks current gen-0 ownership
under an already selected destination; imported leases and endpoint keys survive without another
initial registration. Certified genesis provenance preserves original priority through later joins.
Source resume, abort and an automatic multi-host cutover remain unavailable. No bootstrap becomes
trusted through a migration file or discovery hint.

## 26. Signed Markdown replies

The writer can enable a reply thread for a public Markdown page. Each reply is a separate signed
Markdown document in a canonical JSON envelope. Its target binds the original publication, path,
version, page hash, manifest hash and optional parent reply hash. The reply ID is the BLAKE3 hash
of the canonical envelope. By default, the reply is signed with a pseudonymous key derived for
the publication. The reader can choose to use their public identity instead.

New envelopes are sealed to the writer's X25519 inbox key. Peer request `0x0c` carries a
publication, path and encrypted envelope. It returns the reply digest after durable receipt by the
writer. The acknowledgement does not indicate approval. The writer reviews the exact bytes and
approves them into the next author-signed version. The signed manifest contains the thread file
at `mdw-replies/<BLAKE3 hex of logical page path>.json`. The reader verifies that attachment and
its reply signatures. Saving the public page retains the verified thread for offline reading
and redistribution. Turning off submissions leaves previously approved replies readable.

### Format 2: a comment as a W3C Web Annotation

A new comment is a W3C Web Annotation ([Web Annotation Data Model](https://www.w3.org/TR/annotation-model/))
with a pin and a signature. The first format above stays valid and is still read.

```json
{"annotation":{
   "@context":"http://www.w3.org/ns/anno.jsonld",
   "id":"urn:uuid:3f0c6a52-9d1e-4c7b-8a55-0b2f6e9d4c11",
   "type":"Annotation",
   "motivation":"commenting",
   "creator":"did:key:z6Mk…",
   "created":"2026-11-24T18:30:00Z",
   "body":{"id":"mdw://<publication>/mdw-comments/<page hash>/3f0c6a52-9d1e-4c7b-8a55-0b2f6e9d4c11.md",
           "type":"TextualBody","value":"…Markdown…","format":"text/markdown"},
   "target":{"type":"SpecificResource","source":"mdw://<publication>/<path>",
             "selector":{"type":"TextQuoteSelector","exact":"…","prefix":"…","suffix":"…"}}},
 "pin":{"publication":"…","path":"…","pageHash":"…","manifestHash":"…","version":5,"parent":null},
 "signature":"<hex>"}
```

- **`annotation`** holds nothing of ours. Its members appear in exactly this order, with no others.
  - `@context` is that exact string. It is a fixed identifier: nothing is fetched from it.
  - `id` is `urn:uuid:` and a lower-case UUID. The commenter makes it at random (version 4).
  - `motivation` is `commenting` for a comment on the page, `replying` for an answer to a comment.
  - `creator` is the signing key as a `did:key`: `z`, then base58 (Bitcoin alphabet) of the two bytes
    `0xed 0x01` and the 32-byte Ed25519 public key. The key is the pseudonymous comment key or the
    reader's public identity, as in the first format.
  - `created` is UTC in the form `YYYY-MM-DDTHH:MM:SSZ`.
  - `body.value` is the Markdown, 1 to 16,384 bytes. `body.id` is where the author's site carries that
    Markdown as a document once the comment is approved (below).
  - `target.source` is the page's address: `mdw://`, the publication ID, `/`, and the path with every
    byte outside `A-Z a-z 0-9 - . _ ~ /` percent-encoded in upper-case hex. For an answer it is the `id`
    of the comment answered.
  - `target.selector` is optional and only on a comment on the page: a Text Quote Selector. `exact` is 1
    to 1,024 bytes and not blank; `prefix` and `suffix` are at most 64 bytes each and are left out when
    empty. A reader matches them against the page's rendered text.
- **`pin`** is the first format's target, unchanged: the exact publication, path, page bytes, manifest
  and version the commenter read, and the hash of the comment answered.
- **`signature`** is the creator's Ed25519 signature over the canonical JSON of `{"annotation":…,"pin":…}`,
  in the domain `mdw/1 web annotation`. The first format's domain stays `mdw/1 markdown reply`.
- **The two parts must agree.** A verifier refuses a comment whose `target.source` is not the pinned page
  (or, for an answer, not a `urn:uuid:`), whose `body.id` is not the document address made from the pin
  and the `id`, whose `motivation` and `pin.parent` disagree, or that is not byte for byte its own
  canonical encoding.
- **The comment ID** is still the BLAKE3 hash of the whole signed envelope. `pin.parent` uses it.
- **An answer to a first-format comment** names it by a UUID made from its ID: the first 16 bytes of the
  hash, with the version set to 8 and the RFC 9562 variant.

**What the author's version carries for a page with comments**, all made in one version so no reader sees
one without the others:

| Path | What |
|---|---|
| `mdw-comments/<page hash>.json` | The thread in format 2: every approved comment of either format, the inbox key and the keepers. |
| `mdw-replies/<page hash>.json` | The thread in the first format, for readers that predate format 2: the first-format comments and the same inbox and keepers. |
| `mdw-comments/<page hash>/<uuid>.md` | One per approved comment: its Markdown, as a document of its own. |

- `<page hash>` is the BLAKE3 hex of the logical page path, as before.
- A reader prefers the format 2 thread. If its bytes are unavailable, it can read the first-format
  thread from the same verified version. A reader never substitutes a thread from another version.
- **A page takes comments on a passage** when its format 2 thread is available. With a first-format
  thread, the reader sends a first-format comment and puts the passage above it as quoted lines.
- Within a thread no two comments share an ID or an `id`, an answer comes after the comment it answers,
  and an annotation's `target.source` names that comment's `id`.
- Removing a comment removes it and its answers from both threads and removes their documents, in one
  version. The author's device keeps the signed comment and its Markdown privately.
- Unpublishing the page removes all of these files with it.
- A comment document opens by its address. Comment documents stay out of contents, post lists, feeds,
  search and standalone saves. Saving the parent page keeps the verified thread and its companion
  files when their reconstructed contents match the sizes and hashes in the signed manifest.
- A comments keeper (below) reads its policy from `mdw-replies/`, which every version still carries.

### Inline replies

Approved comments are rendered inline with author attribution and nested replies. The signed thread authorizes each association by reply hash. Each reply retains its own signed body and identity when a comment is removed from the thread. Disabling submissions changes the inbox state while preserving previous associations. Existing signed threads remain readable.

An author may additionally sign up to four `inboxNodes` endpoint IDs into the thread. This is a
voluntary sealed-mail service, distinct from a public saved copy: a keeper operator must explicitly
allow that publication (`xan node --comment-inbox mdw://ID/`) and hold its verified public thread
listing this keeper. Readers try the writer first, then those exact keepers. No keeper is added by
default and a director or relay alone is not a comments keeper.
The operator's policy cache retains current manifests and at most 4 MiB of thread metadata per
publication (32 publications maximum). It does not fetch page/image bodies and sweeps old policy
versions after refresh. The opaque mail quota below is separate from this bounded metadata cache.

- `0x0d` deposits ciphertext: kind, 32-byte publication key, big-endian u16 path byte length, UTF-8
  path and the sealed age envelope (at most 135,168 bytes). An OK answer is the 32-byte BLAKE3
  ciphertext hash, returned only after file and directory persistence succeeds. It confirms
  storage, not writer receipt or approval. The original `0x0c` writer receipt is unchanged.
- `0x0e` collects without deleting: the same publication and length-prefixed path, then a 64-byte
  publication-key signature. The OK body starts with a count byte (0–8); each envelope is a
  big-endian u32 length and those ciphertext bytes. No other reader can enumerate this inbox.
  Batches rotate by ciphertext hash without deleting entries; a writer makes at most eight passes
  per keeper in one review, so invalid mail cannot permanently hide valid replies later in the spool.
- `0x0f` acknowledges collection: publication and path as above, the 32-byte ciphertext hash and
  a 64-byte publication-key signature. The OK answer repeats that hash. The writer sends this
  only after the envelope is decrypted, verified against its original signed page/thread revision
  and durably queued locally. The writer still explicitly approves it into a new signed version.

The `0x0e`/`0x0f` signature domain is `mdw/1 comments inbox control`. Its message is the request
without its final signature, then the keeper's 32-byte endpoint key, then a 32-byte TLS exporter
using that domain as label and the preceding message as exporter context. This binds publication
key possession to the keeper, operation, publication, path, ciphertext hash where applicable, and
fresh QUIC/TLS connection. A proof from another connection, keeper, thread or operation fails.
An identical replay within that same connection is nondestructive collection or an idempotent ack.
The signed manifest's serving routes confer no inbox-control authority.

The opaque spool is separate from blobs, public catalogs, search and approved threads. Each keeper
holds at most 256 envelopes / 16 MiB globally, 64 envelopes / 4 MiB per publication, and eight
envelopes / 512 KiB per authenticated source endpoint across publications. Byte caps include the
stored envelope metadata. Mail expires after seven days;
retries do not extend its original receipt time. Deposits use the normal 60-request/minute source
limit; authenticated collection/ack requests have a 256-request/minute ceiling to drain a full
bounded spool without weakening deposit limits. The ordinary serving
switch apply. A closed or unlisted inbox stops new deposits once the keeper learns its new signed
version; an offline keeper cannot promise immediate revocation. Invalid or unpersisted mail is
never acknowledged away by the writer. Old approved copies remain readable and cannot be recalled.

## 27. Direct DHT routes

A publisher, keeper or director can advertise its public QUIC socket addresses in a Mainline
BEP 44 mutable item keyed by its endpoint key with salt `project-xan/iroh-route/1`. The value is a
space-separated list of up to eight socket addresses. The sequence is Unix time in microseconds.
Readers accept records up to 90 minutes old, with 60 seconds of forward clock tolerance. Public
lookup filters local and special addresses. An isolated test DHT permits only loopback routes.
Iroh authenticates the endpoint before exchanging MDW data. A reader doing ordinary navigation
does not make a direct route announcement.

This supplies a direct path from a publication pointer, keeper advertisement, or director
announcement to the peer. Direct routing can run without an HTTP mirror, a relay, or a vendor
address lookup. Existing relay paths remain available for peers that need NAT traversal.

## 28. Device catalogue detail and private writing sync

The optional byte `0x12` requests the detail catalogue from the same authenticated endpoint used by `0x11`. It answers with deterministic CBOR `[truncated, rows]`. A row contains the publication key, logical path, publication title, landing flag, publisher flag, post title and optional RFC 3339 date as text. An empty date indicates no known publication date. Nodes derive their own role from locally verified publication manifests and report saved copies separately. This is an endpoint's report. The page still verifies against its author when opened. Older endpoints retain their existing `0x0b` and `0x11` response formats.

The optional `0x13` request exchanges a private writing frame between a linked editor and its publishing host. The transport authenticates both endpoints and encrypts the exchange. The host checks the caller's endpoint ID, membership and the private group identifier before reading the workspace or accepting a change. A new member receives a passphrase-encrypted invitation signed by both the owner and the host endpoint, bound to the recipient endpoint, public site identity and expiry. The member checks the host proof against the device ID supplied independently of the file. The invitation contains no signing keys. A revoked endpoint cannot enter the writing service.

Writing frames are bounded UTF-8 JSON. A request contains the group ID, the randomly generated grant from the encrypted invitation and an action to read the inventory, read a block, send a block, delete a file or request publication of one page revision. The host matches the grant's hash against the membership for the authenticated endpoint. Reissuing an invitation creates a new grant. A write declares its expected base, complete content hash, size and sequential block offset. The host verifies exact bytes before replacing a file under the granted folder. Requests carry at most 128 KiB and responses at most 2 MiB. The largest block of file bytes is 64 KiB. An editor uses the last common revisions to distinguish changes authored on each device. Both copies survive an unresolved clash. Public catalogues and content requests see signed snapshots, while writing sync uses the private working pages.

## 29. Private Identity Web

Optional request kind `0x14` on the existing authenticated peer protocol exchanges private JSON request and response records. It shares the normal MDW endpoint routes, including DHT lookup and optional relays. The request payload is bounded to 64 KiB and replies to 128 KiB. A peer without the service gives the ordinary not-found reply. No membership record, pairing credential, or private control request appears in a public directory, catalog or DHT value.

Pairing uses a `mdw-pair:` link containing the exact authority endpoint, an independently random 32-byte secret, and optionally an Iroh endpoint ticket for initial routing. The authority retains the secret's BLAKE3 hash for five minutes. It binds the first accepted request to its authenticated sender. Confirmation compares a short code derived from the hashed secret and both endpoint IDs. The accepted device receives the signed roster. It retains the device's own established keys and no person or publication private key travels in the invitation.

### Pairing by address

**Your identity → Your devices → Pair a device** starts a temporary listener on the selected local or VPN IP address. Enter that address, its TCP port and the eight-digit random code on the other device. A password-authenticated exchange uses SPAKE2 to derive separate keys for the joiner’s confirmation and the encrypted invitation. The listener can try up to six connections over five minutes. The encrypted invitation is the existing endpoint-bound pairing link. It transfers once and the listener closes.


The TCP exchange sends a 33-byte SPAKE2 A message, then a 33-byte B message. The Ed25519 group identity strings are `markmallow lan pairing v1 joiner` and `markmallow lan pairing v1 host`. From the SPAKE2 output, BLAKE3 derive-key makes two 32-byte keys with contexts `Markmallow LAN pairing v1 joiner confirmation` and `Markmallow LAN pairing v1 host invitation`. A sends a 32-byte HMAC-SHA-256 over `markmallow lan pairing v1`. B verifies it before returning the invitation. B sends a big-endian u16 length followed by the invitation encrypted with ChaCha20-Poly1305, a 12-byte zero nonce and the same prologue as associated data. The key encrypts one invitation. Length includes the 16-byte tag. The plaintext is a UTF-8 pairing link of at most 4,400 bytes.

Address pairing uses `pairPreview` (token and device name), `pairConfirm` (token and confirmation code), and the existing `check` over authenticated peer streams. The link flow may fall back to legacy `join` when a host does not answer `pairPreview`. A new link client still checks the confirmation code before installing an approved roster.

Both screens display the same confirmation code. The authority signs membership after both devices confirm the authenticated pair. Cancel and expiry clear pending pairing. Signed membership is stored by device ID. Moving between network routes affects reachability. The device stays in **Your devices** until a signed removal applies. QR scanning and Bluetooth are proposed ways to carry the initial invitation through the same confirmation steps.

The authority signs the deterministic JSON serialization of `{owner,authority,revision,devices}` with domain `mdw identity web roster 1`. A member is `{device,name,manageDirectors}`. The receiver checks the exact introductory endpoint, its own membership and the owner's strict Ed25519 signature. Later lists must have the same owner and authority and a strictly higher revision. Active members can exchange the signed list over authenticated connections. A disconnected peer can retain the last revision it saw. The owner signs revisions on the device that manages the identity.

A member's `name` is for people. It is what the reader called the device, the device's computer name, or a word for what the device is (`Phone`, `Computer`). A list never holds the same name twice: the later one gets a number (`Phone 2`). It never holds the words `This device`, which every device in the list would read as itself. A list that was saved with those words is corrected by the device that manages it, in a new revision. An implementation shows which row is the reading device by its ID.

Linked keepers expose only public saves and accept new copies after a local opt-in. A request carries the original MDW address, signed version and manifest hash. The keeper resolves and verifies the exact requested copy with the regular reader's manifest and blob checks. A success receipt means the keeper has durably recorded the copy in its local library. The author's signature, address and attribution travel with it.

An owned director's mutation uses a separate `mdw identity web director grant 1` signature over caller, expiry, owner roster revision and the target director's exact reviewed action, subject and catalog revision. The authority checks current permission before signing. The target checks the caller and destination against its authenticated connection, signature, lifetime and current local revision. A successful mutation advances the durable revision so the same grant cannot apply again. The owner's authority must be reachable for a fresh remote mutation. Public search and private search credentials provide no admin authorization. These actions change that director's local policy and leave publisher-signed withdrawals unmodified.

An operator can opt a headless `xan node` director into enrollment using `--identity-pair FILE --device-label NAME`. FILE contains the temporary pairing link. The operator compares the code printed on the host before approving. Later restarts use the same device key and its persisted signed roster.
