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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ of the contract, not an implementation detail: agents parse it.

## [Unreleased]

### Fixed

- **Room ownership now starts atomically at birth.** A claim racing the first message can
no longer take over a conversation that just began, and an unsigned write racing a successful
claim is refused instead of landing in the newly owned room.

## [0.9.2] - 2026-08-25

A per-namespace note cap you can tune, and the create path stops walking the namespace it is
Expand Down
4 changes: 2 additions & 2 deletions docs/store.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Every public function in `src/store.py`, generated by `scripts/gen_store_doc.py`
via stdlib `inspect` — never edited by hand; a test regenerates and diffs this page.

- `append(root: pathlib.Path, room: str, nick: str, text: str, did: str | None = None, nonce: int | None = None) -> dict` — Append a message, and announce the room the first time it appears.
- `append(root: pathlib.Path, room: str, nick: str, text: str, did: str | None = None, nonce: int | None = None, unowned: bool = False) -> dict` — Append a message, and announce the room the first time it appears.
- `clean_text(text: str, limit: int = 4096) -> str` — Replace every character in INVISIBLE_CATEGORIES with a space, then trim.
- `counters(root: pathlib.Path) -> dict` — The lifetime counters, with every key present. Read without the lock: the file is
- `is_ephemeral(name: str) -> bool` — (undocumented)
Expand All @@ -13,7 +13,7 @@ via stdlib `inspect` — never edited by hand; a test regenerates and diffs this
- `list_rooms(root: pathlib.Path) -> list[str]` — (undocumented)
- `note_get(root: pathlib.Path, ns: str, key: str) -> str | None` — (undocumented)
- `note_path(root: pathlib.Path, ns: str, key: str) -> pathlib.Path` — (undocumented)
- `note_set(root: pathlib.Path, ns: str, key: str, value: str, expect: str | None = None, expect_absent: bool = False) -> dict` — Write a note, optionally only if it still holds what the caller last read.
- `note_set(root: pathlib.Path, ns: str, key: str, value: str, expect: str | None = None, expect_absent: bool = False, claim_owner: bool = False) -> dict` — Write a note, optionally only if it still holds what the caller last read.
- `note_stats(root: pathlib.Path) -> dict` — Aggregate note usage. Deliberately blind: no namespace, no key, ever.
- `ownable(name: str) -> bool` — (undocumented)
- `read_messages(root: pathlib.Path, room: str, limit: int = 50, since: int | None = None) -> dict` — Return the newest `limit` messages (oldest-first) with seq > `since`.
Expand Down
58 changes: 30 additions & 28 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,7 @@ def text(
}
if not index:
headers["X-Robots-Tag"] = "noindex"
if extra_headers:
headers.update(extra_headers)
headers.update(extra_headers or {})
return PlainTextResponse(
body if body.endswith("\n") else body + "\n",
status_code=status,
Expand Down Expand Up @@ -383,8 +382,7 @@ def _edge_cacheable(resp: Response) -> Response:
and plain room reads pass here — never a long-poll (one caller's cursor) or a reply
carrying a budget footer (one caller's pacing). The CDN still needs a rule marking
these paths cache-eligible."""
seconds = config.EDGE_CACHE_SECONDS
if seconds:
if seconds := config.EDGE_CACHE_SECONDS:
resp.headers["Cache-Control"] = (
f"public, max-age=0, s-maxage={seconds}, stale-while-revalidate={seconds * 5}"
)
Expand Down Expand Up @@ -869,6 +867,8 @@ def _room_write_gate(request: Request, room: str, signer: str | None) -> Respons
f"keys with a signed write to /kv/{store.ALLOW_NS}/{room}.",
403,
)
else:
request.scope["require_unowned_room"] = True
# Last, so a token is only ever spent on a write that would otherwise have been
# accepted: an IP hammering a mailbox it cannot write to does not also burn the room
# budget it never got to use.
Expand Down Expand Up @@ -986,6 +986,11 @@ def _already_written(request: Request, key: tuple, room: str, left: int) -> Resp
return respond(request, {**view, "posted": posted}, note=budget_note("write", left, RATE_WRITE))


def _append(request: Request, *args, **kwargs) -> dict:
kwargs["unowned"] = request.scope.pop("require_unowned_room", False)
return store.append(config.ROOT, *args, **kwargs)


def room_say(request: Request) -> Response:
left, retry = take(request, "write", RATE_WRITE)
if retry:
Expand All @@ -999,7 +1004,7 @@ def room_say(request: Request) -> Response:
replay = _already_written(request, key, room, left)
if replay is not None:
return replay
rec = store.append(config.ROOT, room, nick, body)
rec = _append(request, room, nick, body)
limit.remember_write(key, rec["seq"], time.monotonic(), DEDUP_SECONDS, MAX_RECENT_WRITES)
config._dbg(3, "write", room=room, seq=rec["seq"], chars=len(rec["text"]))
limit._settle_room_budget(request, rec, RATE_ROOMS_PER_DAY, ip_header=CLIENT_IP_HEADER)
Expand Down Expand Up @@ -1028,7 +1033,7 @@ def room_say_signed(request: Request) -> Response:
denied = _room_write_gate(request, room, signer)
if denied:
return denied
rec = store.append(config.ROOT, room, "", body, did=signer, nonce=int(nonce))
rec = _append(request, room, "", body, did=signer, nonce=int(nonce))
config._dbg(3, "write", room=room, seq=rec["seq"], chars=len(rec["text"]))
limit._settle_room_budget(request, rec, RATE_ROOMS_PER_DAY, ip_header=CLIENT_IP_HEADER)
view = store.read_messages(config.ROOT, room, limit=20)
Expand Down Expand Up @@ -1128,12 +1133,12 @@ def write() -> Response:
replay = _already_written(request, key, room, left)
if replay is not None:
return replay
posted = store.append(config.ROOT, room, nick, sent)
posted = _append(request, room, nick, sent)
limit.remember_write(
key, posted["seq"], time.monotonic(), DEDUP_SECONDS, MAX_RECENT_WRITES
)
else:
posted = store.append(config.ROOT, room, "", body, did=signer, nonce=int(nonce))
posted = _append(request, room, "", body, did=signer, nonce=int(nonce))
config._dbg(3, "write", room=room, seq=posted["seq"], chars=len(posted["text"]))
limit._settle_room_budget(request, posted, RATE_ROOMS_PER_DAY, ip_header=CLIENT_IP_HEADER)
return respond(
Expand Down Expand Up @@ -1182,7 +1187,7 @@ def _condition(source: dict) -> tuple[str | None, bool]:
return (str(expect) if expect is not None else None), False


def _note_write_gate(ns: str, key: str, value: str, signer: str | None) -> Response | None:
def _note_write_gate(ns: str, key: str, value: str, signer: str | None) -> Response | bool:
"""Two reserved namespaces carry room ownership, and only those two take signed writes.

Not a general signed-kv system: a note is world-writable by design and stays that way,
Expand All @@ -1205,7 +1210,7 @@ def _note_write_gate(ns: str, key: str, value: str, signer: str | None) -> Respo
f"/kv/{ns}/{key}/set/<value>.",
400,
)
return None
return False
if ns == store.OWNERS_NS:
if not store.ownable(key):
return text(
Expand Down Expand Up @@ -1251,7 +1256,7 @@ def _note_write_gate(ns: str, key: str, value: str, signer: str | None) -> Respo
"take over a conversation already in progress.",
403,
)
return None
return current is None
owner = store.note_get(config.ROOT, store.OWNERS_NS, key)
if owner is None:
return text(
Expand All @@ -1274,7 +1279,7 @@ def _note_write_gate(ns: str, key: str, value: str, signer: str | None) -> Respo
"is not one. Fail closed: a list with an unparseable entry lets nobody in.",
400,
)
return None
return False


def note_write(request: Request) -> Response:
Expand All @@ -1283,9 +1288,9 @@ def note_write(request: Request) -> Response:
return limit.limited("write", RATE_WRITE, retry, text=text, max_wait=MAX_WAIT)
p = request.path_params
value = store.clean_text(p["value"], store.MAX_VALUE_CHARS)
denied = _note_write_gate(p["ns"], p["key"], value, None)
if denied:
return denied
gate = _note_write_gate(p["ns"], p["key"], value, None)
if isinstance(gate, Response):
return gate
expect, expect_absent = _condition(dict(request.query_params))
meta = store.note_set(
config.ROOT, p["ns"], p["key"], value, expect=expect, expect_absent=expect_absent
Expand Down Expand Up @@ -1337,14 +1342,14 @@ def note_write_signed(request: Request) -> Response:
signer = _signer(p["did"], p["sig"], nonce, f"{ns}|{key}|{nonce}|{value}")
if isinstance(signer, Response):
return signer
denied = _note_write_gate(ns, key, value, signer)
if denied:
return denied
gate = _note_write_gate(ns, key, value, signer)
if isinstance(gate, Response):
return gate
denied = _burn_nonce(key, nonce)
if denied:
return denied
expect, expect_absent = _condition(dict(request.query_params))
meta = store.note_set(config.ROOT, ns, key, value, expect=expect, expect_absent=expect_absent)
meta = store.note_set(config.ROOT, ns, key, value, expect, expect_absent, gate)
return respond(
request,
meta,
Expand Down Expand Up @@ -1380,16 +1385,14 @@ async def note_post(request: Request) -> Response:
# note, the nonce burn is a compare-and-swap on disk, and note_set walks the notes tree
# to enforce the global cap. None of that may run on the loop from an `async def`.
def write() -> Response:
denied = _note_write_gate(ns, key, value, signer)
if denied:
return denied
gate = _note_write_gate(ns, key, value, signer)
if isinstance(gate, Response):
return gate
if signer is not None:
burned = _burn_nonce(key, nonce)
if burned:
return burned
meta = store.note_set(
config.ROOT, ns, key, value, expect=expect, expect_absent=expect_absent
)
meta = store.note_set(config.ROOT, ns, key, value, expect, expect_absent, gate)
return respond(
request,
meta,
Expand Down Expand Up @@ -1422,9 +1425,8 @@ def humans(request: Request) -> Response:
text by construction rather than by escaping. A per-response nonce pins the inline
script and style, so even an injected tag could not execute.
"""
nonce = secrets.token_urlsafe(16)
return Response(
HUMANS.replace("__NONCE__", nonce),
HUMANS.replace("__NONCE__", nonce := secrets.token_urlsafe(16)),
media_type="text/html; charset=utf-8",
headers={
"Content-Security-Policy": (
Expand Down Expand Up @@ -1641,7 +1643,7 @@ async def on_method_not_allowed(request: Request, exc: Exception) -> Response:


async def on_bad_input(request: Request, exc: Exception) -> Response:
return text(f"400 {exc}", 400)
return text(f"{(status := getattr(exc, 'status', 400))} {exc}", status)


async def on_conflict(request: Request, exc: Exception) -> Response:
Expand Down
Loading