Files
ai-agent/backend/plugins/hubnotify.py
gabrielvidalandClaude Fable 5.2 32c75c35ae feat(plugins): notify.respond serves a push's own picture, for a phone with no session
GET …/hub/notify/push/{id}/image: the image recorded on the handler's user's
own push, as bytes (image/* only, at most 5 MB). A picture on the hub itself is
read through the file route it names with that route's own check; a public one
through image_proxy.fetch; a lab address is never fetched.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 20:19:16 +01:00

319 lines
14 KiB
Python

"""``notify.respond`` — a phone channel's way back to the hub
(``/proxy/tools/plugins/{pid}/hub/notify/…``, since 2026-11-28, the
``android-push`` plugin).
A ``notify.channel`` plugin delivers a person's pushes and asks to their
phone. When its own app answers — over the plugin's webhook, not a browser
session — the plugin's handler needs to do, **as that person and for their own
pushes only**, what ``/api/ask/{id}/answer``, ``/api/notify/{id}/action`` and
``/api/notifications/dismissed`` do for Home Assistant:
* ``GET …/hub/notify/pairing`` — who the installer is and the addresses
their app can use: ``{user, uid, isOwner, addresses: [{id, label, hub,
hooks: {<webhook id>: <url with its token>}}], origins: [...]}``. The
owner: ``public`` first (``OWNER_HOSTS`` as the app's address, the plugin's
webhooks on the guest host — the owner's host serves no ``/proxy/``), then
``tailnet`` (the admin host for both). A guest: the guest host. ``origins``
are the hub's own origins, for a channel to make a link relative.
* ``GET …/hub/notify/push/{id}`` — one recorded push or ask, whole
(``{push}``: ``id``, ``kind``, ``title``, ``body``, ``options``, ``actions``,
``url``, ``image``, ``type``, ``tag``, ``status``, ``at``…).
* ``GET …/hub/notify/push/{id}/image`` — that push's own picture, as bytes
(``image/*``, at most 5 MB), so the channel can hand the phone a link it can
load with no session: a picture **on the hub itself** is read through the
file route it points at, with that route's own check for this person
(:data:`_OWN_IMAGE_ROUTES` — nothing else is served); a public one is
fetched as ``/api/notify/{id}/image`` does. Never a lab address.
* ``POST …/hub/notify/answer {id, index}`` — answer an ask: ``{ok, label}``;
409 ``answered`` / ``expired`` once it is no longer pending (the first
answer wins), then the hub clears every device as it always does.
* ``POST …/hub/notify/action {id, action | index}`` — a push's button
(``action``: the button's own id, ``<push id>__<i>``): ``{ok, title,
already}``; the first tap wins.
* ``POST …/hub/notify/dismissed {tags}`` — pushes swiped away on the phone:
read in the app (the owner's ledger) and off the person's other devices and
channels — not this plugin's own, where they are already gone.
Every route takes the plugin's **own handler token** only (a guest's run token
can't answer for them), needs the capability, and acts for the token's user:
a push or ask that isn't theirs (``notifications.routes.push_is_for``) is a
404, as if it didn't exist. Not an operator capability — a guest's own install
answers their own asks.
"""
from __future__ import annotations
import os
from typing import Any
from fastapi import APIRouter, Request
from starlette.concurrency import run_in_threadpool
from plugins.hubbridge import _caller_for_who, _check_cap, _json_body
from plugins.proxyroutes import _error
from plugins.store import OWNER_UID
router = APIRouter(include_in_schema=False)
CAP = "notify.respond"
def _ctx(request: Request, pid: str):
"""``(deps, caller, uid, err)`` for a handler of ``pid`` holding the
capability; ``caller`` is the person the handler runs for."""
deps, who, _rec, err = _check_cap(request, pid, CAP, handler_only=True)
if err:
return None, None, None, err
caller = _caller_for_who(deps, who)
if caller is None:
return None, None, None, _error(403, "no such user", "auth")
return deps, caller, (OWNER_UID if who.is_owner else who.uid), None
def _owner_hosts() -> list[str]:
"""``OWNER_HOSTS`` in the order it was written (the first is the one the
app is told), minus the guest hosts — as ``users.caller`` reads it."""
from users.caller import OWNER_HOSTS
seen = [h.strip().lower() for h in os.environ.get("OWNER_HOSTS", "").split(",") if h.strip()]
return [h for h in dict.fromkeys(seen) if h in OWNER_HOSTS]
def addresses(deps, pid: str, uid: str, is_owner: bool) -> dict[str, Any]:
"""The addresses ``uid``'s app can pair with, each with the plugin's
webhook URLs (their own install's tokens)."""
from notifications.service import VIEW_URL
from users.deliver import GUEST_PUBLIC_URL
rec = deps.plugin_store.get_raw(deps.plugin_store.norm_uid(uid), pid) or {}
tokens = rec.get("webhookTokens") or {}
hook_ids = [w["id"] for w in ((rec.get("manifest") or {}).get("webhooks") or [])]
def hooks(base: str) -> dict[str, str]:
return {h: f"{base}/proxy/tools/plugins/{pid}/webhook/{h}?token={tokens.get(h, '')}"
for h in hook_ids}
out: list[dict[str, Any]] = []
owner_hosts = _owner_hosts()
if not is_owner:
base = GUEST_PUBLIC_URL or VIEW_URL
out.append({"id": "public", "label": "Internet", "hub": base, "hooks": hooks(base)})
else:
if owner_hosts:
hub = f"https://{owner_hosts[0]}"
# The owner's host answers no /proxy/ path (its Traefik router
# refuses the machine paths): the webhook goes through the guest
# host, where the tool proxy is served and the token is the auth.
out.append({"id": "public", "label": "Internet", "hub": hub,
"hooks": hooks(GUEST_PUBLIC_URL or hub)})
out.append({"id": "tailnet", "label": "Tailnet", "hub": VIEW_URL, "hooks": hooks(VIEW_URL)})
origins = [VIEW_URL, GUEST_PUBLIC_URL, *(f"https://{h}" for h in owner_hosts)]
return {"addresses": out, "origins": [o for o in dict.fromkeys(origins) if o]}
@router.get("/proxy/tools/plugins/{pid}/hub/notify/pairing")
async def hub_notify_pairing(pid: str, request: Request):
deps, caller, uid, err = _ctx(request, pid)
if err:
return err
return {"user": caller.name, "uid": uid, "isOwner": caller.is_owner,
**addresses(deps, pid, uid, caller.is_owner)}
def _own_entry(deps, caller, nid: str, kind: str | None = None) -> dict | None:
"""The recorded push / ask ``nid`` when it is ``caller``'s own."""
from notifications.routes import push_is_for
store = deps.notify_store
entry = store.ask_status(nid) if kind == "ask" else store.get(nid)
if entry and entry.get("kind") == "ask" and kind is None:
entry = store.ask_status(nid) or entry # its effective status (expired)
if not entry or (kind and entry.get("kind") != kind):
return None
return entry if push_is_for(deps, caller, entry) else None
_PUSH_KEYS = ("id", "kind", "title", "body", "type", "url", "image", "tag", "at",
"sessionId", "options", "status", "answer", "answerIndex", "answeredAt",
"expiresAt", "actions", "actionIndex", "actionTitle", "actedAt")
@router.get("/proxy/tools/plugins/{pid}/hub/notify/push/{nid}")
async def hub_notify_push(pid: str, nid: str, request: Request):
deps, caller, _uid, err = _ctx(request, pid)
if err:
return err
def _go():
from notifications.routes import _with_url
e = _own_entry(deps, caller, nid)
if e is None:
return None
e = _with_url(caller, e)
return {k: e[k] for k in _PUSH_KEYS if e.get(k) not in (None, "", [])}
push = await run_in_threadpool(_go)
if push is None:
return _error(404, "unknown notification", "not_found")
return {"ok": True, "push": push}
# A push's picture on the hub itself is a link to one of these file routes.
# The bridge calls the route's own function with the person it acts for, so
# the route's check is the check; the two that take no caller are the owner's
# (the gate's table, which is not in the way here, keeps guests off them).
def _own_image_routes():
from files import assets, browse
return {
"/api/host-file/raw": lambda c, q: browse.host_file_raw(c, q["path"]),
"/api/artefact": lambda c, q: assets.artefact_asset(c, q["kind"], q["slug"], q["path"]),
"/api/project-asset": lambda c, q: assets.project_asset(c, q["slug"], q["path"]),
"/api/screenshot": lambda c, q: assets.screenshot_asset(q["path"]) if c.is_owner else None,
"/api/data-asset": lambda c, q: assets.data_asset(q["path"]) if c.is_owner else None,
}
_IMAGE_TYPES = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
".webp": "image/webp", ".gif": "image/gif", ".avif": "image/avif"}
def push_image(deps, caller, entry: dict) -> tuple[bytes, str] | None:
"""``(bytes, content type)`` of a recorded push's picture for ``caller``
(whose push it is), or None: no picture, not an image, too big, a lab
address, or a hub path this person may not read."""
import pathlib
from urllib.parse import parse_qsl, urlsplit
from fastapi import HTTPException
from notifications import image_proxy
from notifications.service import VIEW_URL
from users.deliver import GUEST_PUBLIC_URL
url = str(entry.get("image") or "").strip()
if not url:
return None
origins = (VIEW_URL, GUEST_PUBLIC_URL, *(f"https://{h}" for h in _owner_hosts()))
path = image_proxy.own_path(url, origins)
if path is None:
if not image_proxy.is_web(url):
return None
try:
return image_proxy.fetch(url) # public only, image/* only, capped
except image_proxy.ImageError:
return None
parts = urlsplit(path)
fn = _own_image_routes().get(parts.path)
if fn is None:
return None
try:
res = fn(caller, dict(parse_qsl(parts.query)))
except (HTTPException, KeyError):
return None
target = pathlib.Path(str(getattr(res, "path", "") or ""))
ctype = _IMAGE_TYPES.get(target.suffix.lower())
try:
if not ctype or not target.is_file() or target.stat().st_size > image_proxy.MAX_BYTES:
return None
return target.read_bytes(), ctype
except OSError:
return None
@router.get("/proxy/tools/plugins/{pid}/hub/notify/push/{nid}/image")
async def hub_notify_push_image(pid: str, nid: str, request: Request):
deps, caller, _uid, err = _ctx(request, pid)
if err:
return err
def _go():
e = _own_entry(deps, caller, nid)
return push_image(deps, caller, e) if e else None
got = await run_in_threadpool(_go)
if got is None:
return _error(404, "no image", "not_found")
from fastapi.responses import Response
return Response(got[0], media_type=got[1],
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"})
@router.post("/proxy/tools/plugins/{pid}/hub/notify/answer")
async def hub_notify_answer(pid: str, request: Request):
deps, caller, _uid, err = _ctx(request, pid)
if err:
return err
body = await _json_body(request)
nid = str(body.get("id") or "")[:64]
index = body.get("index")
if not nid or isinstance(index, bool) or not isinstance(index, int):
return _error(400, "id and index are required")
def _go():
from notifications.routes import record_ask_answer
ask = _own_entry(deps, caller, nid, "ask")
if ask is None:
return 404, "unknown ask", "not_found"
if ask.get("status") != "pending":
# The first answer won (or it ran out): nothing to record.
st = "expired" if ask.get("status") == "expired" else "answered"
return 409, st, st
if not 0 <= index < len(ask.get("options") or []):
return 400, "no such option", "bad_request"
done = record_ask_answer(deps, nid, index, None)
return 200, (done or {}).get("answer") or "", ""
status, text, kind = await run_in_threadpool(_go)
if status != 200:
return _error(status, text, kind)
return {"ok": True, "id": nid, "index": index, "label": text}
@router.post("/proxy/tools/plugins/{pid}/hub/notify/action")
async def hub_notify_action(pid: str, request: Request):
deps, caller, _uid, err = _ctx(request, pid)
if err:
return err
body = await _json_body(request)
nid = str(body.get("id") or "")[:64]
index = body.get("index")
action = str(body.get("action") or "")
if not nid:
return _error(400, "id is required")
def _go():
from notifications.routes import run_notify_action
n = _own_entry(deps, caller, nid, "notify")
if n is None:
return 404, "unknown notification", "not_found"
actions = n.get("actions") or []
i = index
if isinstance(i, bool) or not isinstance(i, int):
i = next((k for k, a in enumerate(actions) if a.get("action") == action), None)
if i is None or not 0 <= i < len(actions):
return 400, "no such button", "bad_request"
already = n.get("status") == "acted"
done = run_notify_action(deps, nid, i, None) or {}
return 200, {"ok": True, "id": nid, "index": done.get("actionIndex"),
"title": done.get("actionTitle") or "", "already": already}, ""
status, out, kind = await run_in_threadpool(_go)
if status != 200:
return _error(status, out, kind)
return out
@router.post("/proxy/tools/plugins/{pid}/hub/notify/dismissed")
async def hub_notify_dismissed(pid: str, request: Request):
deps, caller, _uid, err = _ctx(request, pid)
if err:
return err
body = await _json_body(request)
tags = body.get("tags")
if not isinstance(tags, list):
return _error(400, "tags must be a list")
tags = [str(t)[:120] for t in tags[:200] if isinstance(t, str) and t]
def _go():
from notifications.routes import dismiss_tags
return dismiss_tags(deps, caller, tags, f"plugin:{pid}"[:64], skip_channel=pid)
out = await run_in_threadpool(_go)
return {"ok": True, "dismissed": out["entries"]}