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>
307 lines
13 KiB
Python
307 lines
13 KiB
Python
"""
|
|
**Web Push** — a guest's ``webpush`` channel (``users/deliver.py``): the
|
|
notification shows up on their phone or desktop even with the app closed.
|
|
|
|
* **Keys** — one VAPID key pair for the app, made on first use and kept in
|
|
``VAPID_KEY_PATH`` (PEM, 0600). Its public half is the
|
|
``applicationServerKey`` every browser subscribes with, so replacing the
|
|
file orphans every subscription (each device then has to turn push on
|
|
again).
|
|
* **Subscriptions** — ``webpush.json`` ``{"subs": {<id>: {...}}}``, one per
|
|
browser that turned push on (``PushManager.subscribe``): ``user``,
|
|
``endpoint``, ``keys`` (``p256dh``, ``auth``), ``label`` (what the browser
|
|
said it was), ``createdAt``, ``lastOkAt``, ``lastError``. The id is a hash
|
|
of the endpoint, so a browser re-subscribing lands on its own row — and
|
|
moves to whoever signed in on it last.
|
|
* **Levels** — ``prefs`` ``{<user>: {<group>: buzz|silent|off}}``, what each
|
|
user wants from each group of push kinds (``users/push_style.py``), the
|
|
same on every device of theirs.
|
|
* **Sending** — :func:`send` encrypts the payload for each of the user's
|
|
devices (``pywebpush``, RFC 8291) and POSTs it to the browser's push
|
|
service. A device the push service says is gone (404/410) is dropped.
|
|
* **Where it may POST** — only a browser vendor's push service
|
|
(:data:`PUSH_HOSTS`), and never a redirect: the endpoint is whatever the
|
|
caller's browser — or the caller — says it is, and a POST from here to
|
|
``127.0.0.1`` is the owner (``core/auth.py``). What went wrong comes back as
|
|
a status code, never the response's text.
|
|
|
|
The payload is what the service worker (``frontend/public/push-sw.js``)
|
|
needs to draw the notification: ``kind`` (notify | ask | form), ``id``,
|
|
``title``, ``body``, ``url``, ``type``, and an ask's ``options``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import os
|
|
import threading
|
|
from urllib.parse import urlsplit
|
|
|
|
from users.store import _JsonFile, _now_iso
|
|
|
|
log = logging.getLogger("ai-agent.webpush")
|
|
|
|
WEBPUSH_PATH = os.environ.get("WEBPUSH_PATH", "/data/webpush.json")
|
|
VAPID_KEY_PATH = os.environ.get("VAPID_KEY_PATH", "/data/webpush-vapid.pem")
|
|
# Who runs this push sender — a mailto: or https: URL (Apple refuses
|
|
# anything else). The guest surface's public URL unless set.
|
|
VAPID_SUBJECT = os.environ.get("VAPID_SUBJECT", "").strip()
|
|
# How long a push service holds a message for a device that is offline.
|
|
TTL_S = int(os.environ.get("WEBPUSH_TTL_S", str(24 * 3600)))
|
|
# A browser can't be asked for more than this many devices per user.
|
|
MAX_DEVICES = 20
|
|
# The push services browsers subscribe with — Chrome and every Chromium
|
|
# (FCM), Firefox, Safari, Edge on Windows. An exact host, or a ``.suffix``.
|
|
# The endpoint is caller-supplied and the hub POSTs to it from inside its
|
|
# own network, so nothing else is taken (``WEBPUSH_EXTRA_HOSTS`` adds some).
|
|
PUSH_HOSTS = ("fcm.googleapis.com", "android.googleapis.com",
|
|
".push.services.mozilla.com", ".push.apple.com",
|
|
".notify.windows.com",
|
|
*(h.strip().lower() for h in
|
|
os.environ.get("WEBPUSH_EXTRA_HOSTS", "").split(",") if h.strip()))
|
|
|
|
_key_lock = threading.Lock()
|
|
_vapid = None
|
|
|
|
|
|
def _b64url(raw: bytes) -> str:
|
|
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
|
|
|
|
|
def _vapid_key():
|
|
"""The app's VAPID key (a py_vapid ``Vapid``), made on first use."""
|
|
global _vapid
|
|
with _key_lock:
|
|
if _vapid is None:
|
|
from py_vapid import Vapid
|
|
try:
|
|
with open(VAPID_KEY_PATH, "rb") as f:
|
|
_vapid = Vapid.from_pem(f.read())
|
|
except FileNotFoundError:
|
|
v = Vapid()
|
|
v.generate_keys()
|
|
os.makedirs(os.path.dirname(VAPID_KEY_PATH) or ".", exist_ok=True)
|
|
tmp = VAPID_KEY_PATH + ".tmp"
|
|
with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
|
|
0o600), "wb") as f:
|
|
f.write(v.private_pem())
|
|
os.replace(tmp, VAPID_KEY_PATH)
|
|
_vapid = v
|
|
return _vapid
|
|
|
|
|
|
def public_key() -> str:
|
|
"""The ``applicationServerKey`` browsers subscribe with (base64url of the
|
|
uncompressed P-256 point)."""
|
|
from cryptography.hazmat.primitives.serialization import (Encoding,
|
|
PublicFormat)
|
|
return _b64url(_vapid_key().public_key.public_bytes(
|
|
Encoding.X962, PublicFormat.UncompressedPoint))
|
|
|
|
|
|
def _subject() -> str:
|
|
if VAPID_SUBJECT:
|
|
return VAPID_SUBJECT
|
|
from users.deliver import GUEST_PUBLIC_URL
|
|
return GUEST_PUBLIC_URL or "mailto:ai-agent@localhost"
|
|
|
|
|
|
def push_service(endpoint: str) -> str | None:
|
|
"""The push service an endpoint is on — its host — when it is one of
|
|
:data:`PUSH_HOSTS` over plain ``https://host/…`` (no credentials, no
|
|
port, no backslash a browser and Python would read differently)."""
|
|
endpoint = endpoint or ""
|
|
if not endpoint.startswith("https://") or len(endpoint) > 2000 \
|
|
or any(c in endpoint for c in "\\@ \t\r\n"):
|
|
return None
|
|
try:
|
|
parts = urlsplit(endpoint)
|
|
host, port = (parts.hostname or "").lower().rstrip("."), parts.port
|
|
except ValueError:
|
|
return None
|
|
if not host or port not in (None, 443):
|
|
return None
|
|
for h in PUSH_HOSTS:
|
|
if host == h or (h.startswith(".") and host.endswith(h)):
|
|
return host
|
|
return None
|
|
|
|
|
|
def sub_id(endpoint: str) -> str:
|
|
return hashlib.sha256(endpoint.encode()).hexdigest()[:16]
|
|
|
|
|
|
def _public(sid: str, s: dict) -> dict:
|
|
"""A device as its user (or the owner) sees it — never the keys."""
|
|
return {"id": sid, "label": s.get("label") or "", "createdAt": s.get("createdAt"),
|
|
"lastOkAt": s.get("lastOkAt"), "lastError": s.get("lastError")}
|
|
|
|
|
|
class PushStore(_JsonFile):
|
|
def __init__(self, path: str):
|
|
super().__init__(path, {"subs": {}, "prefs": {}})
|
|
|
|
def levels(self, uid: str) -> dict:
|
|
with self._lock:
|
|
return dict((self._data.get("prefs") or {}).get(uid) or {})
|
|
|
|
def level(self, uid: str, group: str) -> str:
|
|
from users.push_style import DEFAULTS
|
|
return self.levels(uid).get(group) or DEFAULTS.get(group, "buzz")
|
|
|
|
def set_levels(self, uid: str, levels: dict) -> dict:
|
|
from users.push_style import clean_levels
|
|
with self._lock:
|
|
prefs = self._data.setdefault("prefs", {})
|
|
prefs[uid] = {**(prefs.get(uid) or {}), **clean_levels(levels)}
|
|
self._save()
|
|
return dict(prefs[uid])
|
|
|
|
def of(self, uid: str) -> list[dict]:
|
|
with self._lock:
|
|
return sorted((_public(k, s) for k, s in self._data["subs"].items()
|
|
if s.get("user") == uid),
|
|
key=lambda d: d.get("createdAt") or "")
|
|
|
|
def count(self, uid: str) -> int:
|
|
with self._lock:
|
|
return sum(1 for s in self._data["subs"].values() if s.get("user") == uid)
|
|
|
|
def _subs(self, uid: str) -> list[tuple[str, dict]]:
|
|
with self._lock:
|
|
return [(k, dict(s)) for k, s in self._data["subs"].items()
|
|
if s.get("user") == uid]
|
|
|
|
def add(self, uid: str, sub: dict, label: str = "") -> dict:
|
|
"""Record (or refresh) a browser's subscription for ``uid``."""
|
|
endpoint = str((sub or {}).get("endpoint") or "").strip()
|
|
keys = (sub or {}).get("keys") or {}
|
|
if not push_service(endpoint) or not keys.get("p256dh") or not keys.get("auth"):
|
|
raise ValueError("not a push subscription")
|
|
sid = sub_id(endpoint)
|
|
with self._lock:
|
|
subs = self._data["subs"]
|
|
if sid not in subs and self.count(uid) >= MAX_DEVICES:
|
|
raise ValueError(f"at most {MAX_DEVICES} devices")
|
|
old = subs.get(sid) or {}
|
|
subs[sid] = {"user": uid, "endpoint": endpoint,
|
|
"keys": {"p256dh": str(keys["p256dh"]), "auth": str(keys["auth"])},
|
|
"label": (label or old.get("label") or "").strip()[:80],
|
|
"createdAt": old.get("createdAt") if old.get("user") == uid
|
|
else _now_iso(),
|
|
"lastOkAt": old.get("lastOkAt") if old.get("user") == uid else None,
|
|
"lastError": None}
|
|
self._save()
|
|
return _public(sid, subs[sid])
|
|
|
|
def remove(self, uid: str, sid: str) -> bool:
|
|
with self._lock:
|
|
s = self._data["subs"].get(sid)
|
|
if not s or s.get("user") != uid:
|
|
return False
|
|
del self._data["subs"][sid]
|
|
self._save()
|
|
return True
|
|
|
|
def forget_user(self, uid: str) -> None:
|
|
"""Drop every device and the levels of a deleted user."""
|
|
with self._lock:
|
|
gone = [k for k, s in self._data["subs"].items() if s.get("user") == uid]
|
|
for k in gone:
|
|
del self._data["subs"][k]
|
|
had = (self._data.get("prefs") or {}).pop(uid, None)
|
|
if gone or had is not None:
|
|
self._save()
|
|
|
|
def _mark(self, sid: str, ok: bool, error: str | None = None,
|
|
drop: bool = False) -> None:
|
|
with self._lock:
|
|
s = self._data["subs"].get(sid)
|
|
if s is None:
|
|
return
|
|
if drop:
|
|
del self._data["subs"][sid]
|
|
elif ok:
|
|
s["lastOkAt"], s["lastError"] = _now_iso(), None
|
|
else:
|
|
s["lastError"] = (error or "failed")[:200]
|
|
self._save()
|
|
|
|
|
|
_session = None
|
|
|
|
|
|
def _no_redirect_session():
|
|
"""A ``requests`` session that never follows a redirect: a push service
|
|
answers 201, and a 307 from anything else would re-POST from inside the
|
|
hub's network — to its own loopback, the owner."""
|
|
global _session
|
|
if _session is None:
|
|
import requests
|
|
|
|
class _Session(requests.Session):
|
|
def request(self, method, url, **kwargs):
|
|
kwargs["allow_redirects"] = False
|
|
return super().request(method, url, **kwargs)
|
|
|
|
s = _Session()
|
|
s.trust_env = False # no proxy / netrc from the environment either
|
|
_session = s
|
|
return _session
|
|
|
|
|
|
def _post(sub: dict, data: str, urgency: str):
|
|
"""One encrypted POST to a device's push service (patched in tests)."""
|
|
from pywebpush import webpush
|
|
return webpush({"endpoint": sub["endpoint"], "keys": sub["keys"]}, data=data,
|
|
vapid_private_key=_vapid_key(),
|
|
vapid_claims={"sub": _subject()}, ttl=TTL_S, timeout=10,
|
|
headers={"Urgency": urgency},
|
|
requests_session=_no_redirect_session())
|
|
|
|
|
|
def _failure(status: int | None) -> str:
|
|
"""What a failed push says — to its user and in ``lastError``: the push
|
|
service's status, never its words (or an exception's: both would hand a
|
|
caller-chosen endpoint's answer back to the caller)."""
|
|
return f"push service answered {status}" if status else "push service unreachable"
|
|
|
|
|
|
def send(store: PushStore, uid: str, payload: dict) -> list[dict]:
|
|
"""Push ``payload`` to every device of ``uid``; one result per device
|
|
(``{id, ok, status?, error?, dropped?}``). Blocking — :func:`send_async`
|
|
for the request thread."""
|
|
data = json.dumps(payload, separators=(",", ":"))
|
|
urgency = ("high" if payload.get("kind") in ("ask", "form")
|
|
else "low" if payload.get("kind") == "clear" else "normal")
|
|
out: list[dict] = []
|
|
for sid, sub in store._subs(uid):
|
|
if not push_service(sub.get("endpoint") or ""):
|
|
# Recorded before endpoints were checked: never POSTed to again.
|
|
store._mark(sid, False, drop=True)
|
|
out.append({"id": sid, "ok": False, "status": None,
|
|
"error": "not a push service", "dropped": True})
|
|
continue
|
|
try:
|
|
_post(sub, data, urgency)
|
|
store._mark(sid, True)
|
|
out.append({"id": sid, "ok": True})
|
|
except Exception as exc:
|
|
resp = getattr(exc, "response", None)
|
|
status = getattr(resp, "status_code", None)
|
|
gone = status in (404, 410)
|
|
store._mark(sid, False, _failure(status), drop=gone)
|
|
if not gone:
|
|
# The exception's text goes to the hub's log only.
|
|
log.warning("web push to %s (%s) failed: %s", uid, sid, str(exc)[:300])
|
|
out.append({"id": sid, "ok": False, "status": status,
|
|
"error": _failure(status), **({"dropped": True} if gone else {})})
|
|
return out
|
|
|
|
|
|
def send_async(store: PushStore, uid: str, payload: dict) -> None:
|
|
threading.Thread(target=send, args=(store, uid, payload), daemon=True).start()
|