Files
gabrielvidal c3196ca500 fix(forms): a guest computer only files forms for its own sessions; form HTML leaves srcdoc for a sandboxed page
Form links are https with the form's own id and never framed on the app origin;
/api/diff-blob answers under `CSP: sandbox`; the asset inliner fetches media
routes only; the deploy preview is sandboxed on a same-origin URL. Sandboxed
form HTML is written into /sandbox-frame.html (its own policy) because srcdoc
and blob: documents inherit the shell's script-src. npm audit fix.
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 15:23:05 +01:00

105 lines
4.0 KiB
Python

"""
A push's picture, served from the app (``GET /api/notify/{id}/image``) — what
a web push's ``image`` points at, so every device loads it from the origin it
already trusts instead of the sender's URL:
* on the hub itself (an ``/api/…`` path, or a link on the admin or guest
host) → a redirect to that path on the caller's own host, where their
session and the route's own checks apply;
* on a public host → fetched here and passed on (``image/*`` only, at most
``MAX_BYTES``, redirects re-checked hop by hop) — the device never calls the
third party;
* on a lab / private host (anything not globally routable: the tailnet, the
LAN, loopback) → the owner's browser is sent there (it can reach it, behind
Authelia); a guest gets nothing — the hub never fetches its own network for
them.
"""
from __future__ import annotations
import ipaddress
import socket
from urllib.parse import urljoin, urlsplit
import httpx
MAX_BYTES = 5 * 1024 * 1024
TIMEOUT_S = 8.0
MAX_HOPS = 3
class ImageError(Exception):
pass
def _in_app(path: str) -> str | None:
"""``path`` when a redirect to it stays on this host. A browser reads
``\\`` as ``/`` — ``/\\evil.example`` is ``//evil.example``, another
site — and drops tabs and newlines before parsing."""
if not path.startswith("/") or path[1:2] in ("/", "\\") \
or any(c == "\\" or ord(c) < 0x20 or ord(c) == 0x7f for c in path):
return None
return path
def own_path(url: str, origins: tuple[str, ...]) -> str | None:
"""The in-app path of ``url`` when it points at the hub itself."""
if url.startswith("/"):
return _in_app(url)
for o in origins:
o = (o or "").rstrip("/")
if o and (url == o or url.startswith(o + "/")):
return _in_app(url[len(o):] or "/")
return None
def is_web(url: str) -> bool:
"""An absolute http(s) URL with a host — the only thing a browser may be
redirected to (``//host/x``, ``/\\host/x`` and other schemes are not)."""
try:
parts = urlsplit(url)
except ValueError:
return False
return parts.scheme in ("http", "https") and bool(parts.hostname) \
and not any(c == "\\" or ord(c) <= 0x20 or ord(c) == 0x7f for c in url)
def is_public(url: str) -> bool:
"""Every address the URL's host resolves to is globally routable."""
parts = urlsplit(url)
if parts.scheme not in ("http", "https") or not parts.hostname:
return False
try:
infos = socket.getaddrinfo(parts.hostname, parts.port or None,
type=socket.SOCK_STREAM)
except OSError:
return False
addrs = {info[4][0] for info in infos}
return bool(addrs) and all(ipaddress.ip_address(a.split("%")[0]).is_global
for a in addrs)
def fetch(url: str) -> tuple[bytes, str]:
"""``(body, content type)`` of a public image, or :class:`ImageError`."""
with httpx.Client(timeout=TIMEOUT_S, follow_redirects=False,
headers={"User-Agent": "ai-agent-push-image/1"}) as client:
for _ in range(MAX_HOPS + 1):
if not is_public(url):
raise ImageError("not a public address")
with client.stream("GET", url) as r:
if r.is_redirect:
url = urljoin(url, r.headers.get("location") or "")
continue
if r.status_code != 200:
raise ImageError(f"upstream {r.status_code}")
ctype = (r.headers.get("content-type") or "").split(";")[0].strip()
if not ctype.startswith("image/") or ctype == "image/svg+xml":
raise ImageError(f"not an image ({ctype or 'no type'})")
body = bytearray()
for chunk in r.iter_bytes():
body += chunk
if len(body) > MAX_BYTES:
raise ImageError("too big")
return bytes(body), ctype
raise ImageError("too many redirects")