agents(pr-queue): allow authenticated proxy hosts and show cache dates (#4554)

Remote IDE gateways inject `X-Sidecar-Token` while forwarding external
`Host` and `Origin` headers unchanged to loopback. Because `pr-queue`
rejected non-loopback authorities and omitted dates from toolbar status
labels, proxied panels failed with HTTP 403 and multi-day caches hid
their fetch date.

Accept strict visible-ASCII non-loopback `Host` headers and matching
`http`/`https` `Origin` endpoints in `pr-queue` when `X-Sidecar-Token`
matches (documented in `.agents/rules/python.md`), while preserving
loopback DNS-rebinding guards for unauthenticated requests. Format
toolbar fetch and cache labels with the calendar date alongside the
local time.
diff --git a/.agents/plugins/pr-queue/sidecars/pr_queue/index.html b/.agents/plugins/pr-queue/sidecars/pr_queue/index.html
index 339af9d..41c9d18 100644
--- a/.agents/plugins/pr-queue/sidecars/pr_queue/index.html
+++ b/.agents/plugins/pr-queue/sidecars/pr_queue/index.html
@@ -818,6 +818,23 @@
         return `updated ${days}d ago`;
       }
 
+      function formatFetchedAt(rawTimestamp) {
+        const dt = new Date(rawTimestamp);
+        if (Number.isNaN(dt.getTime())) {
+          return String(rawTimestamp);
+        }
+        const dateOptions = { month: "short", day: "numeric" };
+        if (dt.getFullYear() !== new Date().getFullYear()) {
+          dateOptions.year = "numeric";
+        }
+        const datePart = dt.toLocaleDateString([], dateOptions);
+        const timePart = dt.toLocaleTimeString([], {
+          hour: "2-digit",
+          minute: "2-digit",
+        });
+        return `${datePart}, ${timePart}`;
+      }
+
       function renderCardActions(pr, isStaleCard) {
         const actions = document.createElement("div");
         actions.className = "pr-actions";
@@ -1074,19 +1091,18 @@
         el.countPill.textContent = `${prs.length} PR${prs.length === 1 ? "" : "s"}`;
 
         if (data.fetched_at) {
-          const dt = new Date(data.fetched_at);
-          const hhmm = Number.isNaN(dt.getTime())
-            ? data.fetched_at
-            : dt.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
+          const stamp = formatFetchedAt(data.fetched_at);
           let prefix = "Fetched";
           if (data.stale_cache) {
             prefix = "Offline cache";
           } else if (data.from_cache) {
             prefix = "Cached";
           }
-          el.cacheNote.textContent = `${prefix} ${hhmm}`;
+          el.cacheNote.textContent = `${prefix} ${stamp}`;
+          el.cacheNote.title = String(data.fetched_at);
         } else {
           el.cacheNote.textContent = "";
+          el.cacheNote.title = "";
         }
 
         if (data.error) {
diff --git a/.agents/plugins/pr-queue/sidecars/pr_queue/server.py b/.agents/plugins/pr-queue/sidecars/pr_queue/server.py
index ca6b62b..4a01fb4 100755
--- a/.agents/plugins/pr-queue/sidecars/pr_queue/server.py
+++ b/.agents/plugins/pr-queue/sidecars/pr_queue/server.py
@@ -33,6 +33,7 @@
 import contextlib
 import datetime
 import hmac
+import ipaddress
 import json
 import logging
 import os
@@ -137,6 +138,9 @@
 
 _TITLE_PUNCT_STRIP_CHARS = ".,:;!?()[]{}\"'`~*"
 _HAS_ALNUM_RE = re.compile(r"[A-Za-z0-9]")
+_HOST_LABEL_RE = re.compile(
+    r"^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?)*\.?$"
+)
 _BRACKET_PREFIX_RE = re.compile(r"^(?:\[[^\]]+\]\s*)+")
 _CONVENTIONAL_COMMIT_RE = re.compile(
     r"^\s*(?P<ctype>[A-Za-z]+)(?:\((?P<scope>[^)]+)\))?!?:\s*(?P<rest>.+)$"
@@ -1606,11 +1610,26 @@
             raise PrQueueError("Expected JSON object request body.")
         return {str(k): v for k, v in parsed.items()}
 
+    def _has_valid_secret_token(self, headers: Mapping[str, str]) -> bool:
+        """Checks whether request headers carry a matching secret token.
+
+        Args:
+          headers: Lowercase HTTP request header mapping.
+
+        Returns:
+          `True` when `self.sidecar_token` is set and matches `x-sidecar-token`.
+        """
+        if not self.sidecar_token:
+            return False
+        provided = headers.get("x-sidecar-token", "").strip()
+        return bool(provided) and hmac.compare_digest(
+            provided.encode("utf-8"), self.sidecar_token.encode("utf-8")
+        )
+
     def _token_valid(self, headers: Mapping[str, str]) -> bool:
         if not self.sidecar_token:
             return self._allow_unauthenticated
-        provided = headers.get("x-sidecar-token", "").strip()
-        return bool(provided) and hmac.compare_digest(provided, self.sidecar_token)
+        return self._has_valid_secret_token(headers)
 
     def _allowed_http_hosts(self) -> frozenset[str]:
         bound = self._host.strip("[]").lower()
@@ -1620,37 +1639,102 @@
             return LOOPBACK_HOSTS | frozenset({bound})
         return frozenset({bound})
 
-    def _is_allowed_host(self, headers: Mapping[str, str]) -> bool:
-        raw_host = headers.get("host", "").strip()
-        if not raw_host or any(ch in raw_host for ch in "@/\\?# \t"):
-            return False
+    @staticmethod
+    def _parse_http_host(raw_host: str) -> tuple[str, int | None] | None:
+        """Parses an HTTP Host or Origin authority into `(lowercase_host, port)`.
+
+        Args:
+          raw_host: Raw `Host` header or `Origin` netloc string.
+
+        Returns:
+          `(host, port)` when syntactically valid, or `None` when malformed.
+        """
+        cleaned = raw_host.strip()
+        if not cleaned or cleaned.endswith(":"):
+            return None
+        if any(not (0x21 <= ord(ch) <= 0x7E) or ch in "@/\\?#%" for ch in cleaned):
+            return None
         try:
-            parsed = urlsplit(f"//{raw_host}")
+            parsed = urlsplit(f"//{cleaned}")
             port = parsed.port
         except ValueError:
-            return False
+            return None
         if port is not None and not (1 <= port <= 65535):
+            return None
+        raw_hostname = parsed.hostname or ""
+        if cleaned.startswith("["):
+            try:
+                ipaddress.IPv6Address(raw_hostname)
+            except ValueError:
+                return None
+            return (raw_hostname.lower(), port)
+        host = raw_hostname.lower()
+        if not host or not _HOST_LABEL_RE.fullmatch(host):
+            return None
+        return (host, port)
+
+    def _is_allowed_host(self, headers: Mapping[str, str]) -> bool:
+        parsed_host = self._parse_http_host(headers.get("host", ""))
+        if parsed_host is None:
             return False
-        host = (parsed.hostname or "").strip("[]").lower()
-        return bool(host) and host in self._allowed_http_hosts()
+        host, _port = parsed_host
+        if host in self._allowed_http_hosts():
+            return True
+        # Authenticated IDE gateways reverse-proxy remote browser traffic to
+        # loopback while preserving the external Host and injecting the UI token.
+        return self._has_valid_secret_token(headers)
+
+    @staticmethod
+    def _ports_match_origin(
+        scheme: str, origin_port: int | None, req_port: int | None
+    ) -> bool:
+        """Checks whether Origin and Host ports represent the same endpoint.
+
+        Args:
+          scheme: Validated lowercase Origin scheme (`http` or `https`).
+          origin_port: Explicit TCP port from Origin, or `None` if omitted.
+          req_port: Explicit TCP port from Host, or `None` if omitted.
+
+        Returns:
+          `True` when ports match directly or via scheme default (`80`/`443`).
+        """
+        default_port = 443 if scheme == "https" else 80
+        effective_origin_port = origin_port if origin_port is not None else default_port
+        effective_req_port = req_port if req_port is not None else default_port
+        return effective_origin_port == effective_req_port
 
     def _is_cross_site_browser_request(self, headers: Mapping[str, str]) -> bool:
         sec_fetch = headers.get("sec-fetch-site", "").strip().lower()
         if sec_fetch == "cross-site":
             return True
         origin = headers.get("origin", "").strip()
-        if origin:
-            try:
-                parsed = urlsplit(origin)
-                _ = parsed.port
-            except ValueError:
-                return True
-            if parsed.scheme.lower() not in ("http", "https"):
-                return True
-            origin_host = (parsed.hostname or "").strip("[]").lower()
-            if origin_host not in self._allowed_http_hosts():
-                return True
-        return False
+        if not origin:
+            return False
+        try:
+            parsed = urlsplit(origin)
+        except ValueError:
+            return True
+        scheme = parsed.scheme.lower()
+        if scheme not in ("http", "https"):
+            return True
+        if parsed.path or parsed.query or parsed.fragment:
+            return True
+        parsed_origin_host = self._parse_http_host(parsed.netloc)
+        if parsed_origin_host is None:
+            return True
+        parsed_req_host = self._parse_http_host(headers.get("host", ""))
+        if parsed_req_host is None:
+            return True
+        origin_host, origin_port = parsed_origin_host
+        req_host, req_port = parsed_req_host
+        allowed_hosts = self._allowed_http_hosts()
+        if origin_host in allowed_hosts and req_host in allowed_hosts:
+            return False
+        if not self._has_valid_secret_token(headers):
+            return True
+        if origin_host != req_host:
+            return True
+        return not self._ports_match_origin(scheme, origin_port, req_port)
 
     @staticmethod
     def _parse_positive_int_query_param(
diff --git a/.agents/plugins/pr-queue/sidecars/pr_queue/server_test.py b/.agents/plugins/pr-queue/sidecars/pr_queue/server_test.py
index e765acf..83e976e 100755
--- a/.agents/plugins/pr-queue/sidecars/pr_queue/server_test.py
+++ b/.agents/plugins/pr-queue/sidecars/pr_queue/server_test.py
@@ -1714,6 +1714,8 @@
                 self.assertIn("sanitizeExternalUrl", html_body)
                 self.assertIn("Number.isInteger", html_body)
                 self.assertIn("resolveDaysSinceUpdate", html_body)
+                self.assertIn("formatFetchedAt", html_body)
+                self.assertIn("toLocaleDateString", html_body)
                 self.assertIn("replaceChildren", html_body)
                 self.assertIn("<script nonce=", html_body)
                 self.assertIn("<style nonce=", html_body)
@@ -1781,6 +1783,144 @@
                 doc_status, _hdr, _b = await _send_raw_http(port, cross_site_doc_req)
                 self.assertEqual(doc_status, 200)
 
+                # Reject unauthenticated/bad-token non-loopback Host (DNS rebinding).
+                for unauth_host_hdrs in (
+                    "",
+                    "X-Sidecar-Token: wrong-token\r\n",
+                    "X-Sidecar-Token: \xffbad-token\r\n",
+                ):
+                    rebinding_doc_req = (
+                        "GET / HTTP/1.1\r\n"
+                        "Host: evil.example.com:1234\r\n"
+                        f"{unauth_host_hdrs}"
+                        "Connection: close\r\n\r\n"
+                    ).encode("latin-1")
+                    rebind_status, _hdr, _b = await _send_raw_http(
+                        port, rebinding_doc_req
+                    )
+                    self.assertEqual(rebind_status, 403)
+
+                non_ascii_api_tok_req = (
+                    f"GET /api/config HTTP/1.1\r\n"
+                    f"Host: 127.0.0.1:{port}\r\n"
+                    "X-Sidecar-Token: \xffbad-token\r\n"
+                    "Connection: close\r\n\r\n"
+                ).encode("latin-1")
+                non_ascii_tok_status, _hdr, _b = await _send_raw_http(
+                    port, non_ascii_api_tok_req
+                )
+                self.assertEqual(non_ascii_tok_status, 403)
+
+                # Reject syntactically invalid Host even with valid X-Sidecar-Token.
+                for malformed_host in (
+                    f"evil.example.com@127.0.0.1:{port}",
+                    "127.0.0.1:99999",
+                    "127.0.0.1,evil.example.com",
+                    "evil;bar.example.com",
+                    "example.com:",
+                    "[fe80::1%25eth0]:8080",
+                    "[not-ipv6]:8080",
+                    "host\x7f.example.com",
+                    "host\xff.example.com",
+                ):
+                    bad_tok_host_req = (
+                        "GET / HTTP/1.1\r\n"
+                        f"Host: {malformed_host}\r\n"
+                        f"X-Sidecar-Token: {mock_token}\r\n"
+                        "Connection: close\r\n\r\n"
+                    ).encode("latin-1")
+                    malformed_status, _hdr, _b = await _send_raw_http(
+                        port, bad_tok_host_req
+                    )
+                    self.assertEqual(malformed_status, 403)
+
+                # Allow gateway-proxied external Host when X-Sidecar-Token matches.
+                proxied_doc_req = (
+                    "GET / HTTP/1.1\r\n"
+                    "Host: remote-proxy.example.com\r\n"
+                    f"X-Sidecar-Token: {mock_token}\r\n"
+                    "Sec-Fetch-Site: cross-site\r\n"
+                    "Connection: close\r\n\r\n"
+                ).encode("ascii")
+                pdoc_status, _hdr, _b = await _send_raw_http(port, proxied_doc_req)
+                self.assertEqual(pdoc_status, 200)
+
+                proxied_get_req = (
+                    "GET /api/config HTTP/1.1\r\n"
+                    "Host: remote-proxy.example.com\r\n"
+                    "Origin: https://remote-proxy.example.com\r\n"
+                    "Sec-Fetch-Site: same-origin\r\n"
+                    f"X-Sidecar-Token: {mock_token}\r\n"
+                    "Connection: close\r\n\r\n"
+                ).encode("ascii")
+                pget_status, _hdr, _b = await _send_raw_http(port, proxied_get_req)
+                self.assertEqual(pget_status, 200)
+
+                for proxy_host, proxy_origin in (
+                    ("remote-proxy.example.com", "https://remote-proxy.example.com"),
+                    (
+                        "remote-proxy.example.com:443",
+                        "https://remote-proxy.example.com",
+                    ),
+                    (
+                        "workstation.example.com:45678",
+                        "https://workstation.example.com:45678",
+                    ),
+                ):
+                    proxied_post_req = (
+                        "POST /api/config HTTP/1.1\r\n"
+                        f"Host: {proxy_host}\r\n"
+                        f"Origin: {proxy_origin}\r\n"
+                        "Sec-Fetch-Site: same-origin\r\n"
+                        f"X-Sidecar-Token: {mock_token}\r\n"
+                        "Content-Type: application/json\r\n"
+                        "Content-Length: 2\r\n"
+                        "Connection: close\r\n\r\n{}"
+                    ).encode("ascii")
+                    ppost_status, _hdr, _b = await _send_raw_http(
+                        port, proxied_post_req
+                    )
+                    self.assertEqual(ppost_status, 200)
+
+                # Reject mismatched or malformed Origin even with valid X-Sidecar-Token.
+                for proxy_host, bad_origin in (
+                    ("remote-proxy.example.com", "https://evil.example.com"),
+                    ("remote-proxy.example.com", "http://localhost:9999"),
+                    (
+                        "remote-proxy.example.com",
+                        "https://evil.example.com@remote-proxy.example.com",
+                    ),
+                    (
+                        f"127.0.0.1:{port}",
+                        "https://evil.example.com@127.0.0.1",
+                    ),
+                    (f"127.0.0.1:{port}", "http://127.0.0.1/extra-path"),
+                    (f"127.0.0.1:{port}", "http://127.0.0.1?query=1"),
+                    (f"127.0.0.1:{port}", "http://127.0.0.1#frag"),
+                    (f"127.0.0.1:{port}", "http://127.0.0.1:0"),
+                    (
+                        "remote-proxy.example.com",
+                        "https://remote-proxy.example.com:9999",
+                    ),
+                    (
+                        "workstation.example.com:45678",
+                        "https://workstation.example.com:9999",
+                    ),
+                ):
+                    mismatched_origin_req = (
+                        "POST /api/config HTTP/1.1\r\n"
+                        f"Host: {proxy_host}\r\n"
+                        f"Origin: {bad_origin}\r\n"
+                        f"X-Sidecar-Token: {mock_token}\r\n"
+                        "Content-Type: application/json\r\n"
+                        "Content-Length: 2\r\n"
+                        "Connection: close\r\n\r\n{}"
+                    ).encode("ascii")
+                    morig_status, _hdr, _b = await _send_raw_http(
+                        port, mismatched_origin_req
+                    )
+                    self.assertEqual(morig_status, 403)
+
                 # Wildcard binds must allow loopback Host headers while rejecting external ones.
                 for wildcard_bind in ("0.0.0.0", "::", "[::]", ""):
                     wildcard_srv = server.PrQueueHttpServer(
@@ -2057,6 +2197,25 @@
                 ).encode("ascii")
                 status_big, _hdr, _body = await _send_raw_http(port, oversized_req)
                 self.assertEqual(status_big, 413)
+
+                # Unauthenticated dev mode must keep rejecting non-loopback Host headers.
+                for hdr_extra in ("", "X-Sidecar-Token: arbitrary\r\n"):
+                    unauth_ext_req = (
+                        "GET / HTTP/1.1\r\n"
+                        "Host: evil.example.com\r\n"
+                        f"{hdr_extra}"
+                        "Connection: close\r\n\r\n"
+                    ).encode("ascii")
+                    status_ext, _hdr, _body = await _send_raw_http(port, unauth_ext_req)
+                    self.assertEqual(status_ext, 403)
+                self.assertTrue(
+                    httpd._is_cross_site_browser_request(
+                        {
+                            "host": "evil.example.com",
+                            "origin": "https://evil.example.com",
+                        }
+                    )
+                )
             finally:
                 await httpd.close()
 
diff --git a/.agents/rules/python.md b/.agents/rules/python.md
index b8ad75b..10db65e 100644
--- a/.agents/rules/python.md
+++ b/.agents/rules/python.md
@@ -133,8 +133,10 @@
   (using cryptographic nonces rather than `'unsafe-inline'` for scripts).
   Validate incoming `Host` headers against allowed bind/loopback hosts
   (including loopback hosts for wildcard binds, rejecting userinfo `@` or path
-  chars) and reject `Sec-Fetch-Site: cross-site` and untrusted `Origin` headers
-  on `/api/*` and `/_sidecar/*` routes.
+  chars; non-loopback reverse-proxy `Host` and matching `Origin` endpoints may
+  be accepted only when a configured secret `X-Sidecar-Token` matches via
+  `hmac.compare_digest`) and reject `Sec-Fetch-Site: cross-site` and untrusted
+  `Origin` headers on `/api/*` and `/_sidecar/*` routes.
 * **SQLite `file:` URIs & `LIKE` Wildcards**: Build file-backed SQLite URIs via
   `Path.resolve().as_uri()`, and escape `\`, `%`, and `_` with `ESCAPE '\'` in
   parameterized `LIKE` clauses, plus re-verify exact repo/slug boundaries.