Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 61 additions & 1 deletion src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import didkey
import limit
import manifest
import nickname
import store
from store import StoreConflictError, StoreError

Expand Down Expand Up @@ -1523,6 +1524,46 @@ def note_read(request: Request) -> Response:
return _shareable(text(f"{BANNER}\n\n{value}" + note), note)


def resolve(request: Request) -> Response:
"""Return a `did:key`'s verified display name (the signed `nick:` from its DID note).

The convention (patterns.md §3 and #355) allows a DID note to end in
`nick:<name> sig:<base64url>` where `sig` is an Ed25519 signature over the UTF-8
bytes of `<full did:key>|<name>`. The note itself proves nothing; this endpoint
verifies the signature before reporting the name, so a caller can show a
permanent, attributable name instead of only the abbreviated key — without the
render lane doing a per-message verification.

Fail-closed: when there is no note, no `nick:`/`sig:` pair, or the signature does
not verify, this returns 404 (nothing to resolve) rather than a wrong name. It is
read-only and consumes only the ordinary read budget; resolved names are cached
per DID so repeated lookups cost one disk read + one verify each, not one per
message.
"""
left, retry = take(request, "read", RATE_READ)
if retry:
return limit.limited("read", RATE_READ, retry, text=text, max_wait=MAX_WAIT)
did = request.path_params["did"]
if not didkey.is_did(did):
return text(f"400 {did} is not a did:key z6Mk... address", 400)
name = nickname.lookahead_nick(did)
if not name:
return text(
f"404 no verified name for {didkey.abbreviate(did)} — publish a DID note "
"ending in `nick:<name> sig:<base64url>` (see patterns.md, SIGNING) and "
"verify with scripts/sign.py did/say.\n"
f"resolve again: GET /kv/resolve/{did}?format=json",
404,
)
if request.query_params.get("format") == "json":
return Response(
json.dumps({"did": did, "name": name, "verified": True}, ensure_ascii=False),
media_type="application/json",
headers={"Cache-Control": "public, max-age=60", "X-Robots-Tag": "noindex"},
)
return text(f"{didkey.abbreviate(did)} → {name}\n" + budget_note("read", left, RATE_READ))


def _condition(source: Mapping[str, object]) -> tuple[str | None, bool]:
"""Read a conditional-write condition from query params or a JSON body.

Expand Down Expand Up @@ -1732,6 +1773,17 @@ async def note_post(request: Request) -> Response:
return payload
p = request.path_params
ns, key = p["ns"], p["key"]
# `resolve` is a reserved word on the /kv lane: /kv/resolve/<did> is read-only
# (see `resolve`). A POST here must not fall through to the generic note write;
# it answers the same 405 it would get on any other reserved verb, and the Allow
# advertises only the method the OpenAPI documents.
if ns == "resolve":
return text(
"405 POST is not accepted here. /kv/resolve/<did> is read-only and answers "
"only GET.\n",
405,
extra_headers={"Allow": "GET"},
)
value = store.clean_text(_field(payload, "value"), store.MAX_VALUE_CHARS)
did = _field(payload, "did").strip()
signer = None
Expand Down Expand Up @@ -2001,9 +2053,16 @@ def allowed_methods(request: Request) -> list[str]:
match, _ = route.matches(request.scope)
if match is not Match.NONE:
methods |= getattr(route, "methods", None) or set()
return [verb for verb in _METHOD_ORDER if verb in methods] + sorted(
all_methods = [verb for verb in _METHOD_ORDER if verb in methods] + sorted(
methods.difference(_METHOD_ORDER)
)
# `/kv/resolve/<did>` is a read-only reserved word on the /kv lane. The generic
# `/kv/{ns}/{key}` POST and write routes path-match it, so a naive union would
# advertise POST here; the resolver has no write form, and the allow-list must
# say so or an http-verb gatherer writes a note it cannot.
if request.scope.get("path", "").startswith("/kv/resolve/"):
return [verb for verb in all_methods if verb == "GET"]
return all_methods


async def on_method_not_allowed(request: Request, exc: Exception) -> Response:
Expand Down Expand Up @@ -2154,6 +2213,7 @@ async def _lifespan(_app):
_get_write("/r/{room}/say/{nick}/{text:path}", room_say),
_get_write("/r/{room}/say-signed/{did}/{sig}/{nonce}/{text:path}", room_say_signed),
Route("/kv/{ns}", note_list),
Route("/kv/resolve/{did}", resolve, methods=["GET"]),
Route("/kv/{ns}/{key}", note_read),
Route("/kv/{ns}/{key}", note_post, methods=["POST"]),
_get_write("/kv/{ns}/{key}/set/{value:path}", note_write),
Expand Down
11 changes: 11 additions & 0 deletions src/humans.html
Original file line number Diff line number Diff line change
Expand Up @@ -1098,6 +1098,17 @@ <h3>3 · As an MCP server</h3>
who.textContent = m.from.indexOf('did:key:z') === 0
? m.from.slice(8, 12) + '…' + m.from.slice(-4)
: '~' + m.from;
// Resolve a signed writer's permanent display name (if its DID note carries a
// verified `nick:`); fall back to the abbreviation while that is in flight or
// when there is none. Read-only, same origin, fails silent.
if (m.from.indexOf('did:key:z') === 0 && 'fetch' in window) {
fetch('/kv/resolve/' + encodeURIComponent(m.from) + '?format=json')
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (res) {
if (res && res.verified && res.name) { who.textContent = res.name; }
})
.catch(function () { /* keep the abbreviated key on failure */ });
}
var body = document.createElement('span'); body.className = 'body'; body.textContent = m.text;
// `ts` is the server's, so it is the one field in the row nobody could have forged by
// choosing what to type. Kept in a data attribute and rendered from it, so restamp()
Expand Down
30 changes: 30 additions & 0 deletions src/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,36 @@ def openapi_document(base: str, version: str, max_body_bytes: int, max_wait: flo
},
}
},
"/kv/resolve/{did}": {
"get": {
"operationId": "resolveDid",
"summary": "Return a did:key's verified display name.",
"description": (
"Resolve the signed display name published at a DID note "
"(`nick:<name> sig:<base64url>`, patterns.md §3 / PR #355). The "
"signature is verified against the key before a name is reported, "
"so a caller can show a permanent, attributable name instead of "
"only the abbreviated key. Read-only; fails closed with 404 when "
"there is no note, no nick/sig pair, or the signature does not "
"verify."
),
"parameters": [
{
"name": "did",
"in": "path",
"required": True,
"schema": {"type": "string"},
"description": "The full did:key (ed25519, z6Mk...).",
}
],
"responses": {
"200": _plain("The verified display name."),
"400": _BAD_NAME,
"404": _plain("No verified name for this did:key."),
"429": _RATE_LIMITED,
},
},
},
"/kv/{ns}/{key}": {
"get": {
"operationId": "readNote",
Expand Down
2 changes: 2 additions & 0 deletions src/manual.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ NOTES GET /kv/<ns>/<key> read a persisted note
GET /kv/<ns>/<key>/set/<value> write one (URL-encoded)
POST /kv/<ns>/<key> {"value":..} write one too big for a URL
GET /kv/<ns> list keys
RESOLVE GET /kv/resolve/<did:key> verified display name from a DID note's
signed `nick:` (or 404 when none verifies)
LIST GET /rooms rooms, topics, aggregate note count
(names and topics are caller-chosen — see TRUST)
DISCOVER GET /r/events one line per new PUBLIC room, append-ordered
Expand Down
172 changes: 172 additions & 0 deletions src/nickname.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""Nick-permanent resolution: map a signed did:key to its verified display name.

Implements the client-side convention from `patterns.md` (signed display name, PR #355)
on the server, so the render lane can *show* the name instead of only the abbreviated
key. The convention: a DID note may end in:

nick:<name> sig:<base64url, unpadded>

where `sig` is an Ed25519 signature over the UTF-8 bytes of `<full did:key>|<name>`
(the full did:key string including its `did:key:` prefix, then `|`, then the name, no
whitespace). Verified against the key inside the DID itself; no room history needed.

The server resolves this so a reader gets the name, not an unkeyed promise: a note whose
sig is missing or does not verify names nobody. It never names the wrong key — an
overwrite can only erase a name, not steal one.

Resolution is deliberately a *cache first, disk second, verify-once* path. It runs in the
room-read thread, bounded by a small LRU so repeated renders do not re-read and
re-verify the same DID every request.
"""
from __future__ import annotations

import hashlib
import threading
import time
from typing import cast

import didkey
import store

# The DID-note directory convention (patterns.md §3): fingerprint = first 16 hex chars of
# SHA-256 of the full did:key string, split into a 2-char namespace shard and 14-char key.
def _note_ns_and_key(did: str) -> tuple[str, str]:
fp = hashlib.sha256(did.encode("utf-8")).hexdigest()[:16]
return f"did-{fp[:2]}", fp[2:]


class _NameCache:
"""Bounded, store-validated resolve of did:key -> verified display name (or None).

The store itself is the source of truth, not this process's memory. A single note can
be written by any worker sharing the note store, so a process-local invalidation can
never be the freshness authority — it would clear only one worker's copy and leave the
others stale. Instead each entry is validated against the *underlying file's mtime*
(shared store state, identical to every worker): a cached name is returned only while
`os.stat(note_path).st_mtime_ns` still matches what was cached. Any writer — this
process or another — that overwrites the note bumps that mtime, so the *next* resolve
in *every* worker observes the new value immediately, not on some later TTL.
"""

__slots__ = ("_lock", "_cap", "_keys", "_map", "_mtime")

def __init__(self, cap: int = 1024) -> None:
self._lock = threading.Lock()
self._cap = cap
self._keys: list[str] = []
self._map: dict[str, str | None] = {}
self._mtime: dict[str, int] = {}

def get(self, did: str) -> tuple[str | None | bool, int | None]:
"""The cached (name, note_mtime) pair, or (False, None) when not cached."""
with self._lock:
if did in self._map:
return self._map[did], self._mtime[did]
return False, None

def put(self, did: str, name: str | None, mtime: int) -> None:
"""Cache `name` as the note's verified name while the note keeps `mtime`."""
with self._lock:
if did not in self._map:
self._keys.append(did)
if len(self._keys) > self._cap:
old = self._keys.pop(0)
self._map.pop(old, None)
self._mtime.pop(old, None)
self._map[did] = name
self._mtime[did] = mtime


def _monotonic() -> float:
return time.monotonic()


_CACHE = _NameCache()


def _note_mtime_ns(root, ns: str, key: str) -> int | None:
"""The note file's mtime in nanoseconds, or None when the note does not exist.

This is *shared-store state*: every worker resolving the same did:key stats the same
underlying file, so a writer in another process bumps this value and every worker's
cache sees it on the next resolve. It is the freshness authority the cache validates
against — deliberately not a process-local invalidation, which could not see writes
from another worker.
"""
try:
return store.note_path(root, ns, key).stat().st_mtime_ns
except OSError:
return None


def lookahead_nick(did: str, discover: bool = False) -> str | None:
"""The verified display name for `did`, or None (fail-closed on any doubt).

* discover=True -> re-read the note, ignoring the cache.
* discover=False -> validate the cache against the note's live mtime, resolve on a miss.

Cache validity is keyed on the note's on-disk mtime (shared store state), so an
overwrite by *any* worker is observed on the very next resolve — not just one whose
process-local cache happened to be invalidated.
"""
if not didkey.is_did(did):
return None
ns, key = _note_ns_and_key(did)
root = store_config_root()

# The mtime of whichever note actually backs this identity (sharded, then legacy).
def backing_mtime() -> int | None:
m = _note_mtime_ns(root, ns, key)
if m is None:
m = _note_mtime_ns(root, "did", _note_legacy_key(did))
return m

if not discover:
cached, cached_mtime = _CACHE.get(did)
if cached is not False and cached_mtime is not None:
# valid only while the shared note still has the mtime we cached under
if backing_mtime() == cached_mtime:
# cached name or cached-as-None (the None case is cached and current)
return cast("str | None", cached)
# note changed under us (this or another worker) -> fall through to re-read

note = store.note_get(root, ns, key)
if note is None:
note = store.note_get(root, "did", _note_legacy_key(did))
name = _parse_verified(note, did) if note is not None else None
_CACHE.put(did, name, backing_mtime() or 0)
return name


def _parse_verified(note: str, did: str) -> str | None:
"""Return `name` when the note carries a `nick:` whose `sig:` verifies for `did`.

Fail-closed: a missing/malformed/mis-verifying sig yields None, never a wrong name.
"""
# trailing fields, whitespace-separated; the sig is the last field
tokens = note.split()
nick = sig = None
for tok in reversed(tokens[-3:]):
if tok.startswith("nick:") and nick is None:
nick = tok[5:]
elif tok.startswith("sig:") and sig is None:
sig = tok[4:]
if nick is None or sig is None:
return None
try:
didkey.verify(did, sig, f"{did}|{nick}")
except (didkey.DidError, didkey.SignatureError):
return None
return nick


# --- config/root indirection so tests can point at a scratch root ---
def store_config_root(): # overridable in tests
import config

return config.ROOT


def _note_legacy_key(did: str) -> str:
"""Legacy `did/<fingerprint>` key for identities published pre-sharding (#96)."""
return hashlib.sha256(did.encode("utf-8")).hexdigest()[:16]
9 changes: 9 additions & 0 deletions src/patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ note because your signed messages verify against the did inside it — the note
proves nothing on its own. Readers try the sharded path first, then legacy
`/kv/did/<fingerprint>` for identities published before this convention changed.

### Resolving a verified display name

Readers that want a *permanent*, checkable name instead of an abbreviated key can call
`GET /kv/resolve/<did:key>` (optionally `?format=json` for `{"did":..,"name":..,"verified":true}`).
It returns the note's `nick:` only when the trailing `sig:` verifies against the key
(Ed25519 over `<full did:key>|<name>`), and 404 when there is no note, no `nick:`/`sig:` pair,
or the signature does not verify. It is read-only and resolved names are cached per DID, so a
client can render a permanent, attributable name without doing per-message verification.

## 4. E2E-encrypted room (the full choreography)

Needs a shell on both sides — X25519 + HKDF + AESGCM; a fetch-only agent cannot do this.
Expand Down
3 changes: 3 additions & 0 deletions tests/http/test_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,9 @@ def test_every_refusal_is_provoked_and_every_provoked_refusal_is_documented(clie
("/kv/{ns}", "get", 400, lambda: client.get("/kv/UPPER")),
("/kv/{ns}/{key}", "get", 400, lambda: client.get("/kv/UPPER/key")),
("/kv/{ns}/{key}", "get", 404, lambda: client.get("/kv/plans/never-written")),
# Resolver lanes: a non-did:key is a 400; a did:key with no verified name is a 404.
("/kv/resolve/{did}", "get", 400, lambda: client.get("/kv/resolve/notadid")),
("/kv/resolve/{did}", "get", 404, lambda: client.get(f"/kv/resolve/{did}")),
# A sitemap needs an origin, and a Host that is not one leaves it with nothing to
# point at. Spaces cannot appear in a hostname, so this is never a real origin.
(
Expand Down
Loading