Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(show): admit bounded explicit public server API handlers
Max44666dc8594f
diff --git a/core/show_api.py b/core/show_api.pynew file mode 100644index 000000000..f722d164b--- /dev/null+++ b/core/show_api.py@@ -0,0 +1,225 @@+"""Explicit, bounded admission for trusted public Show server handlers.++This module never executes a handler or supplies sender authentication. The+workspace author opts an exact route into handler-owned authentication.+"""+from __future__ import annotations++import asyncio+import json+import logging+import os+import re+import stat+from dataclasses import dataclass+from pathlib import Path++from starlette.requests import ClientDisconnect, Request++from core.show_pages import ShowPageStore, show_page_dir+from config import paths++logger = logging.getLogger(__name__)+MANIFEST_NAME = ".show-api.json"+MAX_MANIFEST_BYTES = 16 * 1024+MAX_ROUTES = 16+MAX_BODY_BYTES = 1024 * 1024+MAX_RESPONSE_BYTES = 64 * 1024+MAX_FORWARD_HEADERS = 16+MAX_HEADER_NAME_BYTES = 64+MAX_HEADER_VALUE_BYTES = 2048+MAX_REQUEST_HEADER_BYTES = 16 * 1024+MAX_REQUEST_HEADERS = 64+BODY_TIMEOUT_SECONDS = 10.0+TOTAL_TIMEOUT_SECONDS = 30.0+_ROUTE = re.compile(r"api/[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*\Z")+_PUBLIC_PATH = re.compile(rb"/p/([A-Za-z0-9_-]+)/((?:api/)[A-Za-z0-9_/-]+)\Z")+_HEADER = re.compile(r"x-[a-z0-9]+(?:-[a-z0-9]+)*\Z")+_BLOCKED_PREFIXES = ("x-avibe-", "x-vibe-", "x-forwarded-", "x-original-", "x-proxy-", "x-http-")+_BLOCKED_WORDS = {+ "authorization", "authentication", "auth", "cookie", "csrf", "xsrf", "token", "credential", "credentials",+ "secret", "key", "host", "origin", "referer", "connection", "upgrade",+ "transfer", "encoding", "length", "real", "remote", "method",+}+++@dataclass(frozen=True)+class ServerAPIRegistration:+ session_id: str+ share_id: str+ path: str+ module: Path+ max_body_bytes: int+ forward_headers: tuple[str, ...]+++class ServerAPIRequestError(Exception):+ """Only a fixed status crosses the public boundary, never exception text."""++ def __init__(self, status_code: int):+ self.status_code = status_code+ super().__init__("Show server API request rejected")+++def _unique_object(pairs):+ result = {}+ for key, value in pairs:+ if key in result:+ raise ValueError("duplicate declaration key")+ result[key] = value+ return result+++def _metadata_name(value: object) -> str:+ if not isinstance(value, str):+ raise ValueError("invalid metadata name")+ name = value.lower()+ if (+ len(name) > MAX_HEADER_NAME_BYTES+ or not _HEADER.fullmatch(name)+ or name.startswith(_BLOCKED_PREFIXES)+ or _BLOCKED_WORDS.intersection(name.split("-"))+ ):+ raise ValueError("invalid metadata name")+ return name+++def _declarations(workspace: Path) -> list[dict]:+ manifest = workspace / MANIFEST_NAME+ # A FIFO/device must not block a request, and a symlink must stay confined.+ manifest.resolve(strict=True).relative_to(workspace)+ fd = os.open(manifest, os.O_RDONLY | os.O_NONBLOCK)+ with os.fdopen(fd, "rb") as source:+ info = os.fstat(source.fileno())+ if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_MANIFEST_BYTES:+ raise ValueError("invalid manifest file")+ data = source.read(MAX_MANIFEST_BYTES + 1)+ if len(data) > MAX_MANIFEST_BYTES:+ raise ValueError("manifest too large")+ payload = json.loads(data, object_pairs_hook=_unique_object)+ if (+ not isinstance(payload, dict)+ or set(payload) != {"schema_version", "server_to_server"}+ or type(payload["schema_version"]) is not int+ or payload["schema_version"] != 1+ or not isinstance(payload["server_to_server"], list)+ or len(payload["server_to_server"]) > MAX_ROUTES+ ):+ raise ValueError("unsupported declaration")+ seen = set()+ for route in payload["server_to_server"]:+ if not isinstance(route, dict) or set(route) != {+ "path", "method", "auth", "max_body_bytes", "forward_headers",+ }:+ raise ValueError("invalid route declaration")+ path = route["path"]+ if not isinstance(path, str) or len(path) > 256 or not _ROUTE.fullmatch(path) or path in seen:+ raise ValueError("invalid route path")+ seen.add(path)+ if route["method"] != "POST" or route["auth"] != "handler":+ raise ValueError("unsupported route policy")+ limit = route["max_body_bytes"]+ if type(limit) is not int or not 1 <= limit <= MAX_BODY_BYTES:+ raise ValueError("invalid body limit")+ names = route["forward_headers"]+ if not isinstance(names, list) or len(names) > MAX_FORWARD_HEADERS:+ raise ValueError("invalid metadata list")+ names = tuple(_metadata_name(name) for name in names)+ if len(set(names)) != len(names):+ raise ValueError("duplicate metadata name")+ route["forward_headers"] = names+ return payload["server_to_server"]+++def resolve_server_api(raw_path: bytes, method: str, query: bytes = b"") -> ServerAPIRegistration | None:+ """Resolve admission from current page state and files, with no lifecycle writes."""+ if method != "POST" or query or len(raw_path) > 512:+ return None+ match = _PUBLIC_PATH.fullmatch(raw_path)+ if match is None:+ return None+ share_id, route_path = (part.decode("ascii") for part in match.groups())+ if not _ROUTE.fullmatch(route_path):+ return None+ store = ShowPageStore()+ try:+ page = store.get_by_share_id(share_id)+ finally:+ store.close()+ if page is None or page.share_id != share_id or page.visibility != "public":+ return None+ try:+ workspace = show_page_dir(page.session_id).resolve(strict=True)+ workspace.relative_to(paths.get_show_pages_dir().resolve(strict=True))+ declarations = _declarations(workspace)+ for route in declarations:+ if route["path"] != route_path:+ continue+ # Runtime selects api/<path>.ts before directory or root fallbacks.+ module = (workspace / f"{route_path}.ts").resolve(strict=True)+ module.relative_to(workspace)+ if not module.is_file():+ return None+ return ServerAPIRegistration(+ page.session_id, share_id, route_path, module,+ route["max_body_bytes"], route["forward_headers"],+ )+ except FileNotFoundError:+ return None+ except (OSError, ValueError, TypeError, RecursionError):+ logger.warning("Invalid optional Show server API declaration; admission disabled")+ return None+++def server_api_headers(request: Request, registration: ServerAPIRegistration) -> dict[str, str]:+ """Forward only content type and declared non-credential metadata.++ Duplicate headers are rejected before any coalescing by HTTP libraries.+ Browser identity and caller-supplied runtime protocol headers are discarded.+ """+ raw = request.scope.get("headers", [])+ if len(raw) > MAX_REQUEST_HEADERS or sum(len(k) + len(v) for k, v in raw) > MAX_REQUEST_HEADER_BYTES:+ raise ServerAPIRequestError(431)+ headers = {}+ for key, value in raw:+ name = key.decode("latin-1").lower()+ if name in headers:+ raise ServerAPIRequestError(400)+ headers[name] = value.decode("latin-1")+ if headers.get("content-encoding", "identity").lower() != "identity":+ raise ServerAPIRequestError(415)+ connection_fields = {part.strip().lower() for part in headers.get("connection", "").split(",")}+ if connection_fields.intersection(("content-type", *registration.forward_headers)):+ raise ServerAPIRequestError(400)+ length = headers.get("content-length")+ if length is not None:+ if not re.fullmatch(r"[0-9]{1,10}", length) or "transfer-encoding" in headers:+ raise ServerAPIRequestError(400)+ if int(length) > registration.max_body_bytes:+ raise ServerAPIRequestError(413)+ forwarded = {}+ for name in ("content-type", *registration.forward_headers):+ if name not in headers:+ continue+ value = headers[name]+ if len(value) > MAX_HEADER_VALUE_BYTES or any(ord(c) < 32 or ord(c) == 127 for c in value):+ raise ServerAPIRequestError(400)+ forwarded[name] = value+ return forwarded+++async def read_server_api_body(request: Request, registration: ServerAPIRegistration) -> bytes:+ async def read():+ body = bytearray()+ async for chunk in request.stream():+ if len(body) + len(chunk) > registration.max_body_bytes:+ raise ServerAPIRequestError(413)+ body.extend(chunk)+ return bytes(body)++ try:+ return await asyncio.wait_for(read(), BODY_TIMEOUT_SECONDS)+ except asyncio.TimeoutError as exc:+ raise ServerAPIRequestError(408) from exc+ except ClientDisconnect as exc:+ raise ServerAPIRequestError(400) from excdiff --git a/core/show_runtime.py b/core/show_runtime.pyindex f9966150b..6edb467fd 100644--- a/core/show_runtime.py+++ b/core/show_runtime.py@@ -283,6 +283,10 @@ class ShowRuntimeRequestTimeoutError(TimeoutError):"""A proxied Runtime request exceeded its total request deadline."""+class ShowRuntimeResponseLimitError(ValueError):+ """A handler response violates this request's bounded transport policy."""++class ShowRuntimeUnavailableError(RuntimeError):def __init__(self,@@ -1139,10 +1143,17 @@ class ShowRuntimeManager:render_target: str | None = None,timeout_seconds: float | None = None,automatic: bool = True,+ start_if_needed: bool = True,+ max_response_bytes: int | None = None,) -> httpx.Response:base_url = self._base_urlprocess = self._processif base_url is None:+ if not start_if_needed:+ evidence = ShowRuntimeFailureEvidence(ShowRuntimeFailureDimension.RUNTIME, "runtime_unavailable")+ raise ShowRuntimeUnavailableError(+ evidence.reason, classify_show_runtime_failure(evidence), show_runtime_recovery_action(evidence)+ )ready = await self.ensure(automatic=automatic)if not ready.available or not ready.base_url:raise self._unavailable_error(ready)@@ -1183,6 +1194,7 @@ class ShowRuntimeManager:body=body,phase_timeout_seconds=phase_timeout_seconds,total_timeout_seconds=timeout_seconds,+ max_response_bytes=max_response_bytes,)async def request_global(@@ -1230,11 +1242,45 @@ class ShowRuntimeManager:body: bytes | None,phase_timeout_seconds: float,total_timeout_seconds: float | None = None,+ max_response_bytes: int | None = None,) -> httpx.Response:"""Own transport failures and publish their recovery evidence."""try:async with httpx.AsyncClient(timeout=httpx.Timeout(phase_timeout_seconds, connect=5.0)) as client:- request = client.request(method, f"{base_url}{path}", headers=headers, content=body)+ async def bounded_response() -> httpx.Response:+ bounded_headers = {**headers, "accept-encoding": "identity"}+ async with client.stream(method, f"{base_url}{path}", headers=bounded_headers, content=body) as response:+ # Reject compression before iteration: a decoder may allocate+ # arbitrarily large output from a single compressed chunk.+ if response.headers.get("content-encoding", "identity").lower() != "identity":+ raise ShowRuntimeResponseLimitError("Unsupported Show response encoding")+ if len(response.headers) > 64 or sum(+ len(k) + len(v) for k, v in response.headers.raw+ ) > 16 * 1024:+ raise ShowRuntimeResponseLimitError("Show response headers exceed limit")+ length = response.headers.get("content-length")+ if length is not None and (+ len(length) > 10 or not length.isdecimal() or int(length) > max_response_bytes+ ):+ raise ShowRuntimeResponseLimitError("Show response exceeds limit")+ content = bytearray()+ async for chunk in response.aiter_raw():+ if len(content) + len(chunk) > max_response_bytes:+ raise ShowRuntimeResponseLimitError("Show response exceeds limit")+ content.extend(chunk)+ materialized_headers = [+ (k, v) for k, v in response.headers.raw+ if k.lower() not in {b"content-length", b"transfer-encoding", b"content-encoding"}+ ]+ return httpx.Response(+ response.status_code, headers=materialized_headers, content=bytes(content),+ request=response.request,+ )++ request = (+ client.request(method, f"{base_url}{path}", headers=headers, content=body)+ if max_response_bytes is None else bounded_response()+ )if total_timeout_seconds is None:return await requesttry:diff --git a/docs/plans/show-server-api-ingress.md b/docs/plans/show-server-api-ingress.mdindex 0a981196c..92c5f1dbd 100644--- a/docs/plans/show-server-api-ingress.md+++ b/docs/plans/show-server-api-ingress.md@@ -1,6 +1,6 @@# Public Show server API admission-Status: implementation contract approved by PM seskmjhgq2476 on2026-09-18; not deployed. Implementation owner: backend lane sesvfjhjkzzjy. Existing E2E consumer owner: reg/seszbebbz6fwq. Owner requests GitHub push to the existing E2E instance. This contract describes the minimum product capability needed to reuse its existing signed receiver.+Status: implementation contract approved by PM seskmjhgq2476 on2026-09-18; not deployed. Implementation owner: backend lane sesa4968u458k (analyst sesvfjhjkzzjy completed read-only research). Existing E2E consumer owner: reg/seszbebbz6fwq. Owner requests GitHub push to the existing E2E instance. This contract describes the minimum product capability needed to reuse its existing signed receiver.## OutcomeAn explicitly registered public Show POST endpoint can authenticate an ordinary server-to-server request without requiring browser cookies or Origin. All unrelated routes retain their existing protection. A separate webhook-only Show workspace uses this capability; the existing PR report workspace stays private. This page is an ingress artifact, not a second executor or scheduler.@@ -47,6 +47,7 @@ Same external inbox + sole remotePM seszbebbz6fwq. One managed forever Harness d## Accepted product scope- `vibe/ui_server.py`- new `core/show_api.py`+- `core/show_runtime.py`: PM-approved extension on 2026-09-18 to the existing request and transport options only; see implementation mechanics below- `core/show_pages.py` only where required to reuse page/workspace lifecycle- `tests/test_ui_show_pages.py`, `tests/test_ui_server_mutation_protection.py`, new `tests/test_show_api.py`, new `tests/test_show_api_integration.py`- `scripts/check_show_router.mjs` only for reusing its pinned real Runtime integration path@@ -66,5 +67,54 @@ Implement on feat/show-server-api based at4e0214fcd846; open a real non-draftPR,Prepare a pinned installable artifact and rollback/state-preservation/health plan after gates; do not activate ad or change Cloud edge/GitHub hooks/Vault yet. The owner has authorized obtaining working e2e push; any request for remaining authority must identify a concrete necessary action against actual policies, after the result is reviewable. Do not demand approval simply because analysis prose said "separate". A live signing secret and admin-controlled hook registration remain concrete commissioning prerequisites.+## Implementation mechanics and evidence++- A native POST adapter dispatches with `parse_json=False`. The resolver runs+ after existing host/proxy and role hooks and supplies the registration used by+ Origin exemption and forwarding. The same resolver rechecks after upload, so+ revocation or declaration changes during a slow body prevent dispatch. Browser+ POSTs without registration keep legacy JSON parsing and normal protection.+- The resolver reads at most 16 KiB of regular manifest data, accepts at most 16+ unique routes, and requires a concrete confined `api/<path>.ts`. Paths use+ ASCII alphanumeric/underscore/hyphen segments and have a 256-character limit.+ Raw URI aliases and queries do not acquire admission. Manifest parsing rejects+ duplicate keys; invalid optional declarations disable admission.+- Body limits are 1 MiB hard maximum, 10 seconds for upload and 30 seconds for+ the complete registered operation, including capability negotiation and+ response streaming. Requests allow at most 64 header fields / 16 KiB in total,+ with 16 declared metadata names of at most 64 characters and values of at most+ 2048 bytes. Names are case-insensitive `x-` metadata under a fixed exclusion+ policy for credentials, hop/proxy/internal protocol and browser identity.+ Content type is forwarded; the regular Show header allowlist is unchanged.+- Request and response compression are rejected; declared body length is only+ an early bound and actual original bytes are independently counted. Duplicate+ request headers and connection-nominated metadata are controlled failures.+- PM independently approved `core/show_runtime.py` scope after inspecting the+ consuming call chain at `17d5258ac`: `request()` otherwise calls `ensure()` on+ a missing endpoint, `automatic=False` does not prohibit startup, and `status()`+ inspects installation rather than exposing a live endpoint. Existing+ `request(start_if_needed=True, max_response_bytes=None)` defaults retain all+ prior behavior. This ingress passes `False` and 64 KiB. Missing endpoint fails+ before capability probes or lifecycle operations. The existing transport owns+ streaming and process-fenced failure invalidation; oversized/encoded handler+ responses close their stream without invalidating a healthy Runtime.+- Bounded Runtime response materialization recalculates content length and+ removes transfer/encoding framing. The ingress exposes only a generic no-store+ receipt and accepted 2xx/4xx/5xx status, never handler output, redirect headers,+ cookies or exception detail. Redirects and response policy failures return+ 502; unavailable Runtime returns 503. HTTP 204/205 receipts have empty bodies.+- Real integration uses Runtime `5a9a6a52f2ae03611d617a659bfd0c1c32389478`, the+ existing CI fixture pin, through actual HTTP UI -> Runtime -> TS handler ->+ Python signed receiver -> temporary SQLite inbox. It confirms exact non-ASCII,+ whitespace and newline digest, committed 202 receipt, tamper 401 with no new+ row, SHARED identity and revocation. HOME/XDG/config and representative child+ Vault-path writes are test-owned; credentials are synthetic. The existing+ `check_show_router.mjs` invokes this test using its already-built pinned+ Runtime, so mocks are not the only CI boundary evidence.+- Local validation: 594 existing Show/mutation tests passed. Focused new+ registration/admission/transport tests and the pinned real integration passed;+ final PR/CI evidence is recorded in the delivery report. No service deployment,+ signing key commissioning, hook registration or external delivery is claimed.+## Source evidenceAnalysis read Avibe4e0214fcd8460b68751affb3f00f04156d2970d1, Cloud backend9616a2f2e9b372cc762ef59decc972aaa3a89caa and Show Runtime5e31eda3536db3ea4de018fb253d0ed7d5c69a09. Actual installed e2e host is3.1.1.dev0+g4019b704c99a; these are distinct artifacts. Cloud uses hostname tunnel passthrough to UI5123, so no Cloud backend source change is indicated. Current Show API Origin guard and header allowlist block GitHub. Existing staged receiver tests:13passed synthetic/temp/mock, not live dispatch. Full dated recommendation remains a PM investigation artifact outside the branch.diff --git a/scripts/check_show_router.mjs b/scripts/check_show_router.mjsindex 867f65811..ac6b128da 100644--- a/scripts/check_show_router.mjs+++ b/scripts/check_show_router.mjs@@ -20,6 +20,18 @@ if (!values["runtime-root"]) throw new Error("--runtime-root is required")const runtimeRoot = resolve(values["runtime-root"])const { startShowRuntimeServer } = await import(pathToFileURL(join(runtimeRoot, "packages/runtime/dist/server.js")).href)const temporary = await mkdtemp(join(tmpdir(), "avibe-python-router-check-"))+const executablePath = process.env.PATH+for (const key of Object.keys(process.env)) delete process.env[key]+Object.assign(process.env, {+ PATH: executablePath,+ HOME: join(temporary, "home"),+ AVIBE_HOME: temporary,+ XDG_CONFIG_HOME: join(temporary, "config"),+ XDG_DATA_HOME: join(temporary, "data"),+ XDG_CACHE_HOME: join(temporary, "cache-home"),+ XDG_STATE_HOME: join(temporary, "state-home"),+ AVIBE_ALLOW_DEV_STATE_MIGRATION: "1"+})const workspaceRoot = join(temporary, "show")const sessions = ["sesfresh", "seslegacylf", "seslegacycrlf"]const originalRouters = new Map()@@ -143,6 +155,13 @@ export default function Item({ params, query }: PageProps) {`${sessionId}: initialization or rendering changed the editable router`)}console.log(`Show router integration passed: fresh nested SSR, Unicode, queries, links, HTML, private + public; legacy LF/CRLF ${values["legacy-router-ssr"] ? "nested SSR" : "root fallback"}, route fields, read-only root location + static motion; source files unchanged.`)+ if (!values["legacy-router-ssr"]) {+ execFileSync(values.python, ["-m", "pytest", "tests/test_show_api_integration.py", "-q"], {+ cwd: repository,+ env: { ...process.env, AVIBE_SHOW_API_RUNTIME_ROOT: runtimeRoot },+ stdio: "inherit"+ })+ }} finally {await server?.close()await rm(temporary, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })diff --git a/skills/use-show-pages/SKILL.md b/skills/use-show-pages/SKILL.mdindex f94c183ba..66d9008bb 100644--- a/skills/use-show-pages/SKILL.md+++ b/skills/use-show-pages/SKILL.md@@ -2,7 +2,7 @@name: use-show-pagesslug: use-show-pagesdescription: Build, inspect, update, restore, or share Avibe Show Pages for visual explanations, diagrams, reports, or interactive prototypes. Covers the page workspace and its Git history.-version: 0.3.0+version: 0.4.0---# Use Show Pages@@ -38,6 +38,13 @@ For more usage details, run `vibe show --help` or a subcommand help such as `vibFor live runtime, visibility, and URL availability, treat`vibe show status` and the relevant command output as authoritative.+### Public server-to-server handlers++For an explicitly published POST endpoint that authenticates a non-browser+sender, read [Public server APIs](references/server-api.md) before authoring its+`.show-api.json` declaration. Trusted handler code owns sender authentication;+the declaration does not publish a page or install/start its Runtime.+### Show Page workspace historyThese rules apply only to this Session's Show Page workspace and its Avibediff --git a/skills/use-show-pages/references/server-api.md b/skills/use-show-pages/references/server-api.mdnew file mode 100644index 000000000..061c898ee--- /dev/null+++ b/skills/use-show-pages/references/server-api.md@@ -0,0 +1,71 @@+# Public server-to-server handlers++A public Show workspace can explicitly admit an exact POST handler without a+browser Origin or cookies. Use a separate minimal workspace for this purpose;+keep reports and other private pages private. This is an ingress capability,+not an executor, scheduler, or a promise that your handler authenticates safely.++Create `api/github-webhook.ts` with an exported `POST(request)` function, and+place this optional `.show-api.json` at the workspace root:++```json+{+ "schema_version": 1,+ "server_to_server": [+ {+ "path": "api/github-webhook",+ "method": "POST",+ "auth": "handler",+ "max_body_bytes": 1048576,+ "forward_headers": [+ "x-hub-signature-256",+ "x-github-event",+ "x-github-delivery"+ ]+ }+ ]+}+```++Only `POST /p/<current-share-id>/api/github-webhook` is admitted. Obtain the+actual share URL from `vibe show status`; publication requires the user's+corresponding authorization. The declaration does not publish the page.+Private, limited, offline, revoked, undeclared and non-POST paths keep their+existing protection. Removing the declaration revokes future admission.++Paths contain static ASCII letters, digits, `_`, `-` and `/` segments under+`api/`. They must name a real workspace-confined `.ts` file. Queries, encoded+aliases, dynamic paths, trailing slashes and index fallbacks are not admitted.+The optional manifest is limited to 16 KiB and 16 unique routes; invalid or+unsupported declarations disable this admission without preventing startup.++The handler receives original body bytes and content type plus up to 16+explicit metadata headers. Metadata names are ordinary `x-` names (maximum 64+characters); credential, proxy, internal protocol and hop-by-hop names are+forbidden, case-insensitively. Values are limited to 2048 bytes. Duplicate+headers, compressed bodies and requests exceeding the configured body limit+are rejected before handler execution. The hard body cap is 1 MiB; reading has+a 10-second limit and the complete ingress operation has a 30-second deadline.+Request headers have a 16 KiB / 64-field limit.++`auth: handler` assigns authentication and business authorization to your+trusted server code. Validate a sender's signature against original bytes+before parsing payload business data or producing inbox/dispatch effects.+GitHub's HMAC covers the body, not its delivery or event headers. Validate those+separately and coalesce signed replays. Cookies, Authorization, Origin, Referer,+annotation tokens and caller-supplied Runtime identity never reach the handler.+Avibe supplies its isolated `shared` Runtime context.++The response is a status receipt: 2xx returns `{"ok":true}`; 4xx/5xx returns+`{"error":"show_server_api_rejected"}` with the handler's status. Redirects,+invalid response encodings and oversized responses produce a generic 502.+Responses are no-store; handler bodies and response headers are not exposed.+Use 200 or 202 for receipt bodies (HTTP 204/205 have no response body).+Runtime responses are capped at 64 KiB and 16 KiB / 64 header fields.++An unavailable Runtime returns generic 503. Anonymous traffic never installs,+starts or repairs it: prewarm through the authorized Show/Runtime lifecycle+before commissioning. The runtime's package and handler must be available on+the instance; editing this file does not deploy or activate a package. Verify a+real sender delivery, durable inbox write and consumer receipt before declaring+an external integration live.diff --git a/tests/test_show_api.py b/tests/test_show_api.pynew file mode 100644index 000000000..688fbd588--- /dev/null+++ b/tests/test_show_api.py@@ -0,0 +1,359 @@+"""The opt-in boundary is exact, bounded and carries no browser authority."""+import asyncio+import json+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock++import httpx+import pytest+from starlette.requests import Request++from config import paths+from core import show_api, show_runtime+from core.show_pages import ShowPageStore, ensure_show_page_dir+from core.show_runtime import ShowRuntimeContext, ShowRuntimeProtocolEnvelope+from storage.importer import ensure_sqlite_state+from tests.ui_server_test_helpers import _save_config+from vibe import ui_server+++def create_ingress(tmp_path):+ _save_config(tmp_path)+ ensure_sqlite_state()+ store = ShowPageStore()+ try:+ page = store.update_visibility("sesingress", "public")+ finally:+ store.close()+ workspace = ensure_show_page_dir(page.session_id)+ (workspace / "api").mkdir(exist_ok=True)+ (workspace / "api/receive.ts").write_text("export function POST() { return Response.json({ok:true}) }\n")+ manifest = {+ "schema_version": 1,+ "server_to_server": [{+ "path": "api/receive", "method": "POST", "auth": "handler", "max_body_bytes": 1024,+ "forward_headers": ["x-hub-signature-256", "x-github-event", "x-github-delivery"],+ }],+ }+ (workspace / show_api.MANIFEST_NAME).write_text(json.dumps(manifest))+ return SimpleNamespace(page=page, workspace=workspace, manifest=manifest, path=f"/p/{page.share_id}/api/receive")+++def ingress(tmp_path):+ return create_ingress(tmp_path)+++def resolve(ingress, **kwargs):+ return show_api.resolve_server_api(kwargs.get("path", ingress.path).encode(), kwargs.get("method", "POST"), kwargs.get("query", b""))+++def test_registration_tracks_current_lifecycle_and_file(ingress):+ registration = resolve(ingress)+ assert registration.module == ingress.workspace / "api/receive.ts"+ store = ShowPageStore()+ try:+ for visibility in ("private", "offline", "public"):+ store.update_visibility(ingress.page.session_id, visibility)+ assert bool(resolve(ingress)) == (visibility == "public")+ store.rotate_share(ingress.page.session_id)+ assert resolve(ingress) is None+ finally:+ store.close()++[email protected]("tail", ["api/receive/", "api//receive", "api/%72eceive", "api%2freceive", "api/%252freceive", "api/../api/receive", "api/receive.ts", "api/[name]", "api/Receive", "api/other"])+def test_only_canonical_route_acquires_admission(ingress, tail):+ assert resolve(ingress, path=f"/p/{ingress.page.share_id}/{tail}") is None+++def test_only_declared_method_and_public_surface_acquire_admission(ingress):+ for method in ("GET", "HEAD", "PUT", "PATCH", "DELETE", "OPTIONS"):+ assert resolve(ingress, method=method) is None+ assert resolve(ingress, query=b"target=api/receive") is None+ assert resolve(ingress, path="/show/sesingress/api/receive") is None++[email protected]("change", [+ {"method": "GET"}, {"auth": "hmac"}, {"path": "api/*"}, {"max_body_bytes": True},+ {"max_body_bytes": show_api.MAX_BODY_BYTES + 1}, {"max_body_bytes": 0},+ {"forward_headers": ["Authorization"]}, {"forward_headers": ["X-Avibe-Show-Context"]},+ {"forward_headers": ["Cookie"]}, {"forward_headers": ["X-Api-Key"]},+ {"forward_headers": ["x-vibe-show-event-token"]}, {"forward_headers": ["X-Forwarded-Host"]},+ {"forward_headers": ["Connection"]}, {"forward_headers": ["x-event", "X-Event"]},+ {"forward_headers": ["x-" + "a" * 65]}, {"forward_headers": ["x-event"] * 17},+ {"extra": True},+])+def test_invalid_optional_declaration_disables_only_admission(ingress, change):+ ingress.manifest["server_to_server"][0].update(change)+ (ingress.workspace / show_api.MANIFEST_NAME).write_text(json.dumps(ingress.manifest))+ assert resolve(ingress) is None+ store = ShowPageStore()+ try:+ assert store.get(ingress.page.session_id).visibility == "public"+ finally:+ store.close()++[email protected]("contents", ["{", "null", '{"schema_version":1,"schema_version":1,"server_to_server":[]}', " " * (show_api.MAX_MANIFEST_BYTES + 1)])+def test_manifest_read_is_bounded_and_unambiguous(ingress, contents):+ (ingress.workspace / show_api.MANIFEST_NAME).write_text(contents)+ assert resolve(ingress) is None+++def test_all_declarations_must_be_valid(ingress):+ ingress.manifest["server_to_server"] *= show_api.MAX_ROUTES + 1+ (ingress.workspace / show_api.MANIFEST_NAME).write_text(json.dumps(ingress.manifest))+ assert resolve(ingress) is None+++def test_fallback_and_external_symlink_cannot_acquire_admission(ingress, tmp_path):+ module = ingress.workspace / "api/receive.ts"+ module.rename(ingress.workspace / "api/index.ts")+ assert resolve(ingress) is None+ outside = tmp_path / "outside.ts"+ outside.write_text("export function POST() {}")+ module.symlink_to(outside)+ assert resolve(ingress) is None+ module.unlink()+ module.write_text("export function POST() {}")+ manifest = ingress.workspace / show_api.MANIFEST_NAME+ external_manifest = tmp_path / "outside.json"+ manifest.rename(external_manifest)+ manifest.symlink_to(external_manifest)+ assert resolve(ingress) is None+++async def post(ingress, *, headers=None, content=b'{ "message": "hello" }', path=None, method="POST", host="alex.avibe.bot"):+ transport = httpx.ASGITransport(app=ui_server.app, client=("203.0.113.10", 3456))+ async with httpx.AsyncClient(transport=transport, base_url=f"https://{host}") as client:+ return await client.request(method, path or ingress.path, headers=headers, content=content)+++def fake_manager(monkeypatch, response=None):+ manager = SimpleNamespace(request=AsyncMock(return_value=response or httpx.Response(202, content=b"private handler data")))+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)+ return manager+++async def test_public_ingress_preserves_bytes_and_shared_identity(ingress, monkeypatch):+ manager = fake_manager(monkeypatch)+ raw = '{ "中文": "签名 ☃", "spacing": [ 1, 2 ] }\n'.encode()+ headers = {+ "Content-Type": "application/json", "X-Hub-Signature-256": "sha256=fixture",+ "X-Github-Event": "push", "X-Github-Delivery": "fixture-id",+ "Cookie": "owner=fixture", "Authorization": "Bearer fixture", "Origin": "https://evil.test",+ "Referer": "https://evil.test", "X-Avibe-Show-Context": "private", "X-Avibe-Show-Protocol": "999",+ "X-Vibe-Show-Base": "/show/owner/", "X-Vibe-Show-Target": "/private",+ "X-Vibe-Show-Event-Token": "fixture", "X-Unregistered": "value",+ }+ response = await post(ingress, headers=headers, content=raw)+ assert response.status_code == 202+ assert response.json() == {"ok": True}+ assert response.headers["cache-control"] == "no-store"+ assert "set-cookie" not in response.headers+ args, kwargs = manager.request.call_args+ assert args == ("POST", "/sessions/sesingress/app/api/receive")+ assert kwargs["body"] == raw+ assert kwargs["envelope"].context is ShowRuntimeContext.SHARED+ assert kwargs["headers"] == {+ "content-type": "application/json", "x-hub-signature-256": "sha256=fixture",+ "x-github-event": "push", "x-github-delivery": "fixture-id",+ }+ assert kwargs["start_if_needed"] is False+ assert kwargs["max_response_bytes"] == show_api.MAX_RESPONSE_BYTES++[email protected]("headers,expected", [+ ({"content-length": "9999"}, 413), ({"content-length": "-1"}, 400),+ ({"content-encoding": "gzip"}, 415),+ ([("x-hub-signature-256", "a"), ("X-Hub-Signature-256", "b")], 400),+ ([("authorization", "a"), ("Authorization", "b")], 400),+ ({"x-github-event": "a" * 2049}, 400),+ ({"x-unregistered": "a" * 17000}, 431),+])+async def test_header_bounds_precede_body_read(ingress, monkeypatch, headers, expected):+ manager = fake_manager(monkeypatch)+ async def unreadable():+ raise AssertionError("body must not be read")+ yield b""+ response = await post(ingress, headers=headers, content=unreadable())+ assert response.status_code == expected+ manager.request.assert_not_called()+++async def test_streamed_count_enforced_independently_of_length(ingress, monkeypatch):+ manager = fake_manager(monkeypatch)+ async def chunks():+ yield b"x" * 700+ yield b"x" * 700+ raise AssertionError("must stop reading at bound")+ for headers in ({}, {"content-length": "1"}):+ response = await post(ingress, headers=headers, content=chunks())+ assert response.status_code in {400, 413} # HTTPX adds TE to a streamed body.+ manager.request.assert_not_called()+ registration = resolve(ingress)+ messages = iter([{"type": "http.request", "body": b"x" * 1025, "more_body": False}])+ async def receive():+ return next(messages)+ req = Request({"type": "http", "headers": [(b"content-length", b"1")]}, receive)+ assert show_api.server_api_headers(req, registration) == {}+ with pytest.raises(show_api.ServerAPIRequestError) as exc:+ await show_api.read_server_api_body(req, registration)+ assert exc.value.status_code == 413+++async def test_body_and_whole_request_deadlines(ingress, monkeypatch):+ manager = fake_manager(monkeypatch)+ monkeypatch.setattr(show_api, "BODY_TIMEOUT_SECONDS", 0.02)+ async def stalled():+ await asyncio.sleep(1)+ yield b"x"+ assert (await post(ingress, content=stalled())).status_code == 408+ manager.request.assert_not_called()+ monkeypatch.setattr(show_api, "TOTAL_TIMEOUT_SECONDS", 0.02)+ manager.request.side_effect = lambda *a, **k: None+ async def slow(*args, **kwargs):+ await asyncio.sleep(1)+ manager.request.side_effect = slow+ assert (await post(ingress)).status_code == 504+++async def test_revocation_during_upload_prevents_dispatch(ingress, monkeypatch):+ manager = fake_manager(monkeypatch)+ async def revoked():+ (ingress.workspace / show_api.MANIFEST_NAME).unlink()+ yield b"{}"+ assert (await post(ingress, content=revoked())).status_code == 404+ manager.request.assert_not_called()+++async def test_unopted_browser_and_host_protections_remain(ingress, monkeypatch):+ manager = fake_manager(monkeypatch)+ for path in [ingress.path + "/", ingress.path + "?target=x", ingress.path.replace("receive", "other"), "/api/config"]:+ response = await post(ingress, path=path)+ assert response.status_code in {401, 403}+ assert (await post(ingress, host="other.test")).status_code == 503+ manager.request.assert_not_called()+ (ingress.workspace / show_api.MANIFEST_NAME).unlink()+ assert (await post(ingress)).status_code == 403+ # The existing browser route still validates JSON and then forwards normally.+ assert (await post(ingress, headers={"Origin": "https://alex.avibe.bot", "Content-Type": "application/json"}, content=b"{")).status_code == 400+ assert (await post(ingress, headers={"Origin": "https://alex.avibe.bot"})).status_code == 202+ assert "start_if_needed" not in manager.request.call_args.kwargs+++async def test_private_metadata_file_is_not_public(ingress):+ response = await post(ingress, method="GET", content=b"", path=f"/p/{ingress.page.share_id}/.show-api.json")+ assert response.status_code == 404+ assert "server_to_server" not in response.text+++async def test_no_start_is_request_scoped_and_does_not_probe_or_write(ingress, tmp_path, monkeypatch):+ manager = show_runtime.ShowRuntimeManager(runtime_dir=tmp_path / "never-created", auto_install=True)+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)+ ensure = AsyncMock(side_effect=AssertionError("anonymous admission cannot start/install"))+ negotiate = AsyncMock(side_effect=AssertionError("unavailable runtime must not probe"))+ monkeypatch.setattr(manager, "ensure", ensure)+ monkeypatch.setattr(manager, "_negotiate_context_key_capability", negotiate)+ response = await post(ingress)+ assert response.status_code == 503+ ensure.assert_not_called()+ negotiate.assert_not_called()+ assert not manager.runtime_dir.exists()+ # A subsequent authorized/default caller still invokes the normal lifecycle.+ with pytest.raises(AssertionError, match="cannot start"):+ await manager.request("GET", "/sessions/sesingress/app/", envelope=ShowRuntimeProtocolEnvelope(ShowRuntimeContext.PRIVATE))+ ensure.assert_awaited_once_with(automatic=True)+ assert paths.get_vibe_remote_dir().is_relative_to(tmp_path)+ assert Path.home().is_relative_to(tmp_path)+++class RecordingStream(httpx.AsyncByteStream):+ def __init__(self, chunks):+ self.chunks = chunks+ self.reads = 0+ self.closed = False++ async def __aiter__(self):+ for chunk in self.chunks:+ self.reads += 1+ yield chunk++ async def aclose(self):+ self.closed = True++[email protected]("headers,chunks,expected_reads", [+ ({}, [b"123", b"456", b"never"], 2), ({"content-length": "6"}, [b"never"], 0),+ ({"content-encoding": "gzip"}, [b"compressed-bomb"], 0),+])+async def test_response_limit_closes_stream_without_invalidating_runtime(tmp_path, monkeypatch, headers, chunks, expected_reads):+ manager = show_runtime.ShowRuntimeManager(runtime_dir=tmp_path)+ manager._base_url = "http://127.0.0.1:55555"+ monkeypatch.setattr(manager, "_negotiate_context_key_capability", AsyncMock())+ stream = RecordingStream(chunks)+ transport = httpx.MockTransport(lambda request: httpx.Response(200, headers=headers, stream=stream))+ original_client = httpx.AsyncClient+ monkeypatch.setattr(show_runtime.httpx, "AsyncClient", lambda **kwargs: original_client(transport=transport, **kwargs))+ with pytest.raises(show_runtime.ShowRuntimeResponseLimitError):+ await manager.request("POST", "/sessions/sesingress/app/api/receive", envelope=ShowRuntimeProtocolEnvelope(ShowRuntimeContext.SHARED), start_if_needed=False, max_response_bytes=5)+ assert stream.closed and stream.reads == expected_reads+ assert manager._base_url == "http://127.0.0.1:55555"+++async def test_bounded_response_materializes_consistent_headers(tmp_path, monkeypatch):+ manager = show_runtime.ShowRuntimeManager(runtime_dir=tmp_path)+ manager._base_url = "http://127.0.0.1:55555"+ monkeypatch.setattr(manager, "_negotiate_context_key_capability", AsyncMock())+ stream = RecordingStream([b"hello"])+ transport = httpx.MockTransport(lambda request: httpx.Response(503, headers={"transfer-encoding": "chunked"}, stream=stream))+ original_client = httpx.AsyncClient+ monkeypatch.setattr(show_runtime.httpx, "AsyncClient", lambda **kwargs: original_client(transport=transport, **kwargs))+ response = await manager.request("POST", "/sessions/sesingress/app/api/receive", envelope=ShowRuntimeProtocolEnvelope(ShowRuntimeContext.SHARED), start_if_needed=False, max_response_bytes=5)+ assert response.content == b"hello"+ assert response.headers["content-length"] == "5"+ assert "transfer-encoding" not in response.headers+ assert stream.closed and manager._base_url+++async def test_handler_auth_sees_even_non_json_original_bytes(ingress, monkeypatch):+ manager = fake_manager(monkeypatch, httpx.Response(401, content=b"fixture secret/error"))+ response = await post(ingress, content=b"{ malformed \xff", headers={"Content-Type": "application/json"})+ assert response.status_code == 401+ assert manager.request.call_args.kwargs["body"] == b"{ malformed \xff"+ assert response.json() == {"error": "show_server_api_rejected"}+ assert "fixture" not in response.text+++async def test_hop_by_hop_metadata_is_not_forwarded(ingress, monkeypatch):+ manager = fake_manager(monkeypatch)+ response = await post(ingress, headers={"Connection": "X-Github-Event", "X-Github-Event": "push"})+ assert response.status_code == 400+ manager.request.assert_not_called()+++async def test_total_deadline_covers_runtime_capability_lock(ingress, monkeypatch, tmp_path):+ manager = show_runtime.ShowRuntimeManager(runtime_dir=tmp_path / "runtime")+ manager._base_url = "http://127.0.0.1:55555"+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)+ monkeypatch.setattr(show_api, "TOTAL_TIMEOUT_SECONDS", 0.03)+ transport = AsyncMock(side_effect=AssertionError("lock has not admitted transport"))+ monkeypatch.setattr(manager, "_request_runtime_transport", transport)+ async with manager._capability_lock:+ response = await post(ingress)+ assert response.status_code == 504+ assert response.headers["cache-control"] == "no-store"+ assert manager._base_url == "http://127.0.0.1:55555"+ transport.assert_not_called()++[email protected]("status", [202, 401, 500, 302])+async def test_handler_responses_are_secret_free_and_never_redirect(ingress, monkeypatch, status):+ fake_manager(monkeypatch, httpx.Response(status, content=b"secret payload", headers={"location": "https://login.test", "set-cookie": "secret=value"}))+ response = await post(ingress)+ assert response.status_code == (502 if status == 302 else status)+ assert response.json() == ({"ok": True} if status == 202 else {"error": "show_server_api_rejected"})+ assert "location" not in response.headers and "set-cookie" not in response.headers+ assert response.headers["cache-control"] == "no-store"diff --git a/tests/test_show_api_integration.py b/tests/test_show_api_integration.pynew file mode 100644index 000000000..cfc0cc9e8--- /dev/null+++ b/tests/test_show_api_integration.py@@ -0,0 +1,150 @@+"""Real HTTP producer/consumer check, run by check_show_router.mjs in CI.++Set AVIBE_SHOW_API_RUNTIME_ROOT to a built checkout at the existing CI Runtime+pin to run this standalone. No installed runtime, credentials or services used.+"""+import asyncio+import hashlib+import hmac+import json+import os+from pathlib import Path+import shlex+import shutil+import socket+import sqlite3+import subprocess+import sys+import textwrap++import httpx+import pytest+import uvicorn++from config import paths+from core import show_runtime+from tests.test_show_api import create_ingress+from vibe import ui_server++RUNTIME_SHA = "5a9a6a52f2ae03611d617a659bfd0c1c32389478"+++async def test_real_ui_runtime_signed_handler_inbox(tmp_path, monkeypatch):+ configured = os.environ.get("AVIBE_SHOW_API_RUNTIME_ROOT")+ if not configured:+ pytest.skip("Real Runtime is exercised by the pinned show-router-integration CI job")+ runtime = Path(configured).resolve()+ assert subprocess.check_output(["git", "-C", str(runtime), "rev-parse", "HEAD"], text=True).strip() == RUNTIME_SHA+ cli = runtime / "packages/runtime/dist/cli.js"+ assert cli.is_file(), "Build the pinned Runtime first"+ ingress = create_ingress(tmp_path)+ inbox = tmp_path / "inbox.sqlite"+ secret = "synthetic-show-api-test-secret"+ receiver = tmp_path / "receiver.py"+ receiver.write_text(textwrap.dedent('''\+ import base64, hashlib, hmac, json, os, pathlib, sqlite3, sys+ envelope = json.load(sys.stdin)+ body = base64.b64decode(envelope["body"])+ signature = envelope["headers"].get("x-hub-signature-256", "")+ expected = "sha256=" + hmac.new(os.environ["SHOW_API_FIXTURE_SECRET"].encode(), body, hashlib.sha256).hexdigest()+ if not hmac.compare_digest(expected, signature):+ print(401)+ sys.exit(0)+ payload = json.loads(body)+ assert payload["message"] == "中文 ☃"+ # Representative child writes remain inside this test's HOME/config/Vault.+ for name in ("HOME", "AVIBE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"):+ root = pathlib.Path(os.environ[name])+ assert root.is_relative_to(pathlib.Path(os.environ["SHOW_API_FIXTURE_ROOT"]))+ marker = pathlib.Path(os.environ["AVIBE_HOME"]) / "vault" / "fixture-write"+ marker.parent.mkdir(parents=True, exist_ok=True)+ marker.write_text("synthetic")+ with sqlite3.connect(os.environ["SHOW_API_FIXTURE_INBOX"]) as db:+ db.execute("create table if not exists inbox (digest text primary key, headers text)")+ db.execute("insert or ignore into inbox values (?, ?)", (hashlib.sha256(body).hexdigest(), json.dumps(envelope["headers"])))+ print(202)+ '''))+ (ingress.workspace / "api/receive.ts").write_text(textwrap.dedent(f'''\+ import {{ spawnSync }} from "node:child_process"+ export async function POST(request: Request) {{+ const body = Buffer.from(await request.arrayBuffer()).toString("base64")+ const headers = Object.fromEntries(request.headers)+ const result = spawnSync({json.dumps(sys.executable)}, [{json.dumps(str(receiver))}], {{+ input: JSON.stringify({{body, headers}}), encoding: "utf8"+ }})+ if (result.status !== 0) return Response.json({{error: "fixture failed"}}, {{status: 503}})+ return Response.json({{private: "must never reach the sender"}}, {{status: Number(result.stdout.trim())}})+ }}+ '''))+ # Child commands inherit only synthetic test state, never the Agent shell's+ # tokens, proxies, CLI/Vault settings, or runtime override variables.+ safe_env = {name: os.environ[name] for name in (+ "PATH", "HOME", "AVIBE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME",+ )}+ for name in tuple(os.environ):+ monkeypatch.delenv(name, raising=False)+ for name, value in safe_env.items():+ monkeypatch.setenv(name, value)+ monkeypatch.setenv("SHOW_API_FIXTURE_SECRET", secret)+ monkeypatch.setenv("SHOW_API_FIXTURE_ROOT", str(tmp_path))+ monkeypatch.setenv("SHOW_API_FIXTURE_INBOX", str(inbox))+ monkeypatch.setenv("AVIBE_ALLOW_DEV_STATE_MIGRATION", "1")+ node = shutil.which("node")+ assert node+ manager = show_runtime.ShowRuntimeManager(+ command=shlex.join([node, str(cli)]), workspace_root=paths.get_show_pages_dir(),+ runtime_dir=tmp_path / "runtime", auto_install=False, offline=True,+ )+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)+ # Authorized activation owns startup. Anonymous requests never do.+ listener = socket.socket()+ listener.bind(("127.0.0.1", 0))+ port = listener.getsockname()[1]+ server = uvicorn.Server(uvicorn.Config(ui_server.app, host="127.0.0.1", port=port, lifespan="off", log_level="error"))+ task = None+ try:+ ready = await manager.ensure()+ assert ready.available, ready.reason+ task = asyncio.create_task(server.serve(sockets=[listener]))+ for _ in range(100):+ if server.started:+ break+ await asyncio.sleep(0.02)+ assert server.started+ body = '{ "message": "中文 ☃",\n "values": [ 1, 2 ] }\n'.encode()+ signature = "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()+ headers = {+ "Host": "alex.avibe.bot", "Content-Type": "application/json",+ "X-Hub-Signature-256": signature, "X-Github-Event": "push", "X-Github-Delivery": "fixture-delivery",+ "Authorization": "Bearer synthetic", "Cookie": "owner=synthetic",+ "X-Avibe-Show-Context": "private", "X-Vibe-Show-Base": "/show/owner/",+ }+ async with httpx.AsyncClient(base_url=f"http://127.0.0.1:{port}", trust_env=False, timeout=30) as client:+ accepted = await client.post(ingress.path, headers=headers, content=body)+ assert accepted.status_code == 202, accepted.text+ assert accepted.json() == {"ok": True}+ assert accepted.headers["cache-control"] == "no-store"+ assert "set-cookie" not in accepted.headers+ with sqlite3.connect(inbox) as db:+ rows = db.execute("select digest, headers from inbox").fetchall()+ assert len(rows) == 1 and rows[0][0] == hashlib.sha256(body).hexdigest()+ forwarded = json.loads(rows[0][1])+ assert forwarded["x-avibe-show-context"] == "shared"+ assert forwarded["x-avibe-show-protocol"] == "1"+ assert forwarded["x-vibe-show-base"] == f"/p/{ingress.page.share_id}/"+ assert "authorization" not in forwarded and "cookie" not in forwarded+ tampered = await client.post(ingress.path, headers=headers, content=body + b" ")+ assert tampered.status_code == 401+ assert tampered.json() == {"error": "show_server_api_rejected"}+ with sqlite3.connect(inbox) as db:+ assert db.execute("select count(*) from inbox").fetchone()[0] == 1+ (ingress.workspace / ".show-api.json").unlink()+ revoked = await client.post(ingress.path, headers=headers, content=body)+ assert revoked.status_code == 403+ assert (paths.get_vibe_remote_dir() / "vault/fixture-write").read_text() == "synthetic"+ finally:+ server.should_exit = True+ if task is not None:+ await asyncio.wait_for(task, 10)+ listener.close()+ manager.stop()diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex e3366263f..a494d5a57 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -622,6 +622,8 @@ def _trusted_public_origin_local_request(config: V2Config | None) -> bool:def _is_mutation_guard_exempt() -> bool:+ if getattr(request._request.state, "show_server_api_registration", None) is not None:+ return Trueif request.path in {"/auth/callback","/auth/show-identity/callback",@@ -676,6 +678,8 @@ def _is_show_api_mutation() -> bool:def _ensure_csrf_cookie(response: Response) -> Response:+ if getattr(request._request.state, "show_server_api_registration", None) is not None:+ return responseif _is_current_immutable_static_asset_request():return responseif response.headers.getlist("Set-Cookie"):@@ -2941,6 +2945,22 @@ def enforce_project_role_capabilities():return None[email protected]_request+async def resolve_public_show_server_api():+ # Host/proxy and role hooks above run first. Only the native POST adapter+ # opts into this resolver; legacy/browser routes retain their old contract.+ if not getattr(request._request.state, "show_server_api_candidate", False):+ return None+ from core.show_api import resolve_server_api++ incoming = request._request+ incoming.state.show_server_api_registration = await asyncio.to_thread(+ resolve_server_api, incoming.scope.get("raw_path", b""), incoming.method,+ incoming.scope.get("query_string", b""),+ )+ return None++@app.before_requestdef protect_mutating_ui_requests():if request.method not in MUTATING_METHODS:@@ -15916,6 +15936,87 @@ def redirect_public_show_page_to_canonical_path(share_id):store.close()+def _show_server_api_result(status_code: int):+ # No handler payload, error, response headers or browser tokens cross back+ # through this ingress. The HTTP status is the receipt protocol.+ response = (+ FastAPIResponse(content=b"") if status_code in {204, 205}+ else jsonify({"ok": True} if 200 <= status_code < 300 else {"error": "show_server_api_rejected"})+ )+ response.status_code = status_code+ response.headers["Cache-Control"] = "no-store"+ response.headers["X-Content-Type-Options"] = "nosniff"+ return response+++async def _serve_show_server_api(starlette_request: FastAPIRequest, registration):+ from core import show_api+ from core.show_runtime import (+ ShowRuntimeContext, ShowRuntimeProtocolEnvelope, ShowRuntimeRequestTimeoutError,+ ShowRuntimeResponseLimitError, ShowRuntimeUnavailableError, get_show_runtime_manager,+ )++ try:+ headers = show_api.server_api_headers(starlette_request, registration)+ body = await show_api.read_server_api_body(starlette_request, registration)+ # Revalidate after waiting for the body: publication or the manifest may+ # have been revoked. Use the same resolver, never a second admission rule.+ current = await asyncio.to_thread(+ show_api.resolve_server_api, starlette_request.scope.get("raw_path", b""), "POST",+ starlette_request.scope.get("query_string", b""),+ )+ if current != registration:+ return _show_server_api_result(404)+ proxied = await get_show_runtime_manager().request(+ "POST", f"/sessions/{quote(registration.session_id, safe='')}/app/{registration.path}",+ envelope=ShowRuntimeProtocolEnvelope(ShowRuntimeContext.SHARED),+ headers=headers, body=body, base_path=f"/p/{registration.share_id}/",+ start_if_needed=False, max_response_bytes=show_api.MAX_RESPONSE_BYTES,+ timeout_seconds=show_api.TOTAL_TIMEOUT_SECONDS,+ )+ status = proxied.status_code+ if not (200 <= status < 300 or 400 <= status < 600):+ status = 502+ return _show_server_api_result(status)+ except show_api.ServerAPIRequestError as exc:+ return _show_server_api_result(exc.status_code)+ except ShowRuntimeResponseLimitError:+ return _show_server_api_result(502)+ except ShowRuntimeRequestTimeoutError:+ return _show_server_api_result(504)+ except ShowRuntimeUnavailableError:+ return _show_server_api_result(503)+ except Exception:+ logger.warning("Show server API request failed")+ return _show_server_api_result(503)++[email protected]("/p/{share_id}/{asset_path:path}", include_in_schema=False)+async def public_show_post(starlette_request: FastAPIRequest, share_id: str, asset_path: str):+ from core.show_api import TOTAL_TIMEOUT_SECONDS++ starlette_request.state.show_server_api_candidate = True+ started = time.monotonic()++ async def handler():+ registration = getattr(starlette_request.state, "show_server_api_registration", None)+ if registration is not None:+ try:+ return await asyncio.wait_for(+ _serve_show_server_api(starlette_request, registration),+ timeout=max(0, TOTAL_TIMEOUT_SECONDS - (time.monotonic() - started)),+ )+ except asyncio.TimeoutError:+ return _show_server_api_result(504)+ # Preserve legacy JSON validation for non-opted-in browser POSTs, after+ # the normal Origin/CSRF/visibility hooks have made their decisions.+ request._body_present = bool(await starlette_request.body())+ await request.load_json()+ return await serve_public_show_page(share_id, asset_path)++ return await app.dispatch_native_request(starlette_request, handler, parse_json=False)++@app.route("/p/<share_id>/",defaults={"asset_path": ""},