Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
66 changes: 65 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 @@ -1656,6 +1697,8 @@ def note_write(request: Request) -> Response:
if denied:
return denied
meta = store.note_set(config.ROOT, p["ns"], p["key"], value, *_condition(request.query_params))
if p["ns"] == "did" or p["ns"].startswith("did-"):
nickname.invalidate_all_did_namespace()
return respond(
request,
meta,
Expand Down Expand Up @@ -1732,6 +1775,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 All @@ -1754,6 +1808,8 @@ def write() -> Response:
if burned:
return burned
meta = store.note_set(config.ROOT, ns, key, value, *condition)
if ns == "did" or ns.startswith("did-"):
nickname.invalidate_all_did_namespace()
return respond(
request,
meta,
Expand Down Expand Up @@ -2001,9 +2057,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 +2217,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
170 changes: 170 additions & 0 deletions src/nickname.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"""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

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, expiring resolve of did:key -> verified display name (or None).

The store itself is the source of truth; this is only a bounded in-memory mirror so a
50-message room read does not re-read + re-verify the same DID every request. Entries
expire after a short TTL, and the note-write path calls :meth:`invalidate` so a just
overwritten DID note is reflected on the *next* resolve instead of on some later
eviction. A short-lived stale name is acceptable (the TTL is the generous /humans
cache window for a name that would be verified again on the next read); a permanently
stale one is not — which is exactly what expiry + write-path invalidation prevent.
"""

__slots__ = ("_lock", "_cap", "_keys", "_map", "_ts", "_ttl")

def __init__(self, cap: int = 1024, ttl_ms: int = 30_000) -> None:
self._lock = threading.Lock()
self._cap = cap
self._keys: list[str] = []
self._map: dict[str, str | None] = {}
self._ts: dict[str, float] = {}
self._ttl = ttl_ms / 1000.0

def get(self, did: str) -> str | None | bool:
"""The cached name, None when cached-unresolved, False when not cached/expired."""
now = _monotonic()
with self._lock:
age = self._ts.get(did)
if did in self._map and age is not None and (now - age) < self._ttl:
return self._map[did]
return False

def put(self, did: str, name: str | None) -> None:
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._ts.pop(old, None)
self._map[did] = name
self._ts[did] = _monotonic()

def invalidate(self, did: str) -> None:
"""Drop any cached result for `did` so the next resolve re-reads the note."""
with self._lock:
self._map.pop(did, None)
self._ts.pop(did, None)

def invalidate_all(self) -> None:
"""Drop every cached result (used when a DID-note namespace is rewritten).

DID-note keys are content fingerprints, not reverse-mappable to a did:key, so a
single overwrite cannot target one entry cheaply — but DID notes are written
rarely, so clearing the whole (small) DID cache on any such write is simpler than
a per-key scan and costs nothing in practice. Non-did namespaces are untouched.
"""
with self._lock:
self._map.clear()
self._ts.clear()
self._keys.clear()


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


_CACHE = _NameCache()


def invalidate(did: str) -> None:
"""Drop the cached result for `did`; call after the DID note is rewritten."""
_CACHE.invalidate(did)


def invalidate_all_did_namespace() -> None:
"""Clear the DID cache when a DID-note namespace is written (see _NameCache)."""
_CACHE.invalidate_all()


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 (used by a fresh collector).
* discover=False -> consult the bounded cache first, resolve from disk on a miss.
"""
if not didkey.is_did(did):
return None
if not discover:
cached: str | None | bool = _CACHE.get(did)
if cached is not False:
# cached name or cached-as-None (bool True is impossible; None is valid)
return None if cached is True else cached
ns, key = _note_ns_and_key(did)
note = store.note_get(store_config_root(), ns, key)
if note is None:
# also try legacy single `did` namespace for pre-sharding identities
note = store.note_get(store_config_root(), "did", _note_legacy_key(did))
name = _parse_verified(note, did) if note is not None else None
_CACHE.put(did, name)
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