Files
gabrielvidal b000f4f8e0 fix(guests): push endpoints are push services, a ceiling on wrong sign-in codes, a Bash switch for No-project chats
Any https endpoint was accepted and a 307 from it re-POSTed to the hub's own
loopback as the owner. Sign-in codes: 10 wrong per address a day, 20 per IP in
10 min, 4 mails per address an hour, sent off the request thread. `scratchBash`
per guest (on by default) sets scope.noBash when off. Caps on guest ui-state
and drafts; the host-file secret filter follows links; enroll and terminal
claims re-checked.
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 15:23:05 +01:00

140 lines
5.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Composer drafts kept on the server, per user — what makes a prompt started on
the phone continue at the desk (the frontend's ``lib/drafts``, a
``RichDraftStore`` for ``@gabvdl/ui``'s composer).
One record per (user, key): ``{value, updatedAt, device}``. Keys are the
composer's own — ``draft:<draftKey>`` (the live draft: text, tags, files) and
``drafts:<draftKey>`` (the *Save as draft* shelf), with ``draftKey`` =
``spawn:<profileId>`` (the home composer, one per profile) or
``resume:<sessionId>`` (a conversation's reply box). The value is the
composer's JSON string; the backend only checks it is JSON and not too big.
Last write wins (``updatedAt`` is the server's clock); ``device`` names the
tab that wrote it so that tab ignores its own echo. A deleted key is simply
gone — a client reconciles a missing key on its next full read.
Single JSON file (``/data/drafts.json``), whole-file rewrite on each change
(atomic temp + rename) — a few hundred small records at most.
"""
from __future__ import annotations
import json
import os
import pathlib
import re
import threading
import time
KEY_RE = re.compile(r"^drafts?:[A-Za-z0-9_.:-]{1,160}$")
DEVICE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
#: A shelf of 100 drafts with their attachments' metadata stays far below.
MAX_VALUE = 512 * 1024
#: Per user; past it the stalest records go first.
MAX_KEYS = 400
#: Per user, all their values together: the file is one blob rewritten on
#: every write, so 400 keys × 512 KB of one user must not be what it holds.
#: Past it the stalest records go first, like MAX_KEYS.
MAX_TOTAL = 8 * 1024 * 1024
def valid_key(key: str) -> bool:
return bool(KEY_RE.match(key or ""))
def clean_device(device: str | None) -> str:
return device if device and DEVICE_RE.match(device) else ""
class DraftStore:
def __init__(self, path: str):
self.path = pathlib.Path(path)
self._lock = threading.Lock()
self._data: dict[str, dict[str, dict]] = {}
self._load()
def _load(self) -> None:
try:
raw = json.loads(self.path.read_text(encoding="utf-8"))
except (OSError, ValueError):
raw = {}
data: dict[str, dict[str, dict]] = {}
for uid, recs in (raw.items() if isinstance(raw, dict) else ()):
if not isinstance(recs, dict):
continue
keep = {k: r for k, r in recs.items()
if valid_key(k) and isinstance(r, dict) and isinstance(r.get("value"), str)}
if keep:
data[str(uid)] = keep
self._data = data
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".json.tmp")
tmp.write_text(json.dumps(self._data, separators=(",", ":"), sort_keys=True),
encoding="utf-8")
os.replace(tmp, self.path)
@staticmethod
def _view(key: str, rec: dict) -> dict:
return {"key": key, "value": rec["value"], "updatedAt": int(rec.get("updatedAt") or 0),
"device": rec.get("device") or ""}
def list(self, uid: str) -> list[dict]:
with self._lock:
recs = self._data.get(uid) or {}
return sorted((self._view(k, r) for k, r in recs.items()),
key=lambda d: -d["updatedAt"])
def get(self, uid: str, key: str) -> dict | None:
with self._lock:
rec = (self._data.get(uid) or {}).get(key)
return self._view(key, rec) if rec else None
def put(self, uid: str, key: str, value: str, device: str = "",
now_ms: int | None = None) -> dict:
"""Store ``value`` (a JSON string) — raises ValueError on a bad key,
a value too big or not JSON."""
if not valid_key(key):
raise ValueError("bad key")
if len(value.encode("utf-8")) > MAX_VALUE:
raise ValueError("too big")
try:
json.loads(value)
except ValueError as e:
raise ValueError("not json") from e
at = int(now_ms if now_ms is not None else time.time() * 1000)
with self._lock:
recs = self._data.setdefault(uid, {})
# Never go back in time: two writes in one millisecond keep order.
prev = recs.get(key)
if prev and int(prev.get("updatedAt") or 0) >= at:
at = int(prev["updatedAt"]) + 1
recs[key] = {"value": value, "updatedAt": at, "device": clean_device(device)}
if len(recs) > MAX_KEYS:
for k, _ in sorted(recs.items(), key=lambda kv: kv[1].get("updatedAt") or 0)[
: len(recs) - MAX_KEYS]:
if k != key:
del recs[k]
total = sum(len(r["value"]) for r in recs.values())
if total > MAX_TOTAL:
for k, r in sorted(recs.items(), key=lambda kv: kv[1].get("updatedAt") or 0):
if total <= MAX_TOTAL:
break
if k != key:
total -= len(r["value"])
del recs[k]
self._save()
return self._view(key, recs[key])
def delete(self, uid: str, key: str) -> bool:
with self._lock:
recs = self._data.get(uid) or {}
if key not in recs:
return False
del recs[key]
if not recs:
self._data.pop(uid, None)
self._save()
return True