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 limited guests locally (#1504)
Call Whitee7fc0a0abb80
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 144c5ed99..9589ad1dc 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -260,6 +260,13 @@ scenarios:layer: scenariobackend: webtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_organization_remote_session_recovers_and_revokes_without_oauth+ - id: AUTH-SETUP-404+ name: Verified limited Show Page identity completes local guest admission+ status: covered+ kind: happy_path+ layer: scenario+ backend: show_identity+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_limited_show_identity_closed_loop_installs_guest_lease- id: AUTH-SETUP-210name: Lost Model Hub OAuth start response converges on one provider flowstatus: covereddiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 0ad528c7e..afb2029d8 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -12,7 +12,9 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, patchimport httpx+import jwtimport pytest+from cryptography.hazmat.primitives.asymmetric import rsaROOT = Path(__file__).resolve().parents[3]sys.path.insert(0, str(ROOT))@@ -33,6 +35,7 @@ from config.v2_config import ()from core.agent_auth_service import AgentAuthServicefrom core.handlers.model_hub.service import ModelHubError+from core.show_pages import ShowPageStorefrom modules.agents.codex.agent import CodexAgentfrom tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcessfrom tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep@@ -42,6 +45,7 @@ from tests.scenario_harness.organization_management import (OrganizationManagementScenarioHarness,)from tests.scenario_harness.show_page_email_access import ShowPageEmailAccessScenarioHarness+from tests.ui_server_test_helpers import _save_configfrom storage import remote_access_authorization_servicefrom vibe import cloud_managementfrom tests.scenario_harness.model_hub_native_oauth import (@@ -58,7 +62,7 @@ from vibe.claude_config import (materialize_claude_subprocess_env,read_claude_settings_env,)-from vibe import remote_access, ui_server+from vibe import remote_access, show_identity, ui_serverfrom vibe.ui_server import app@@ -103,6 +107,111 @@ class ShowPageEmailAccessScenarioTests(unittest.TestCase):)+def test_limited_show_identity_closed_loop_installs_guest_lease(monkeypatch, tmp_path):+ """Scenario: AUTH-SETUP-404"""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ cloud = config.remote_access.vibe_cloud+ cloud.backend_url = "https://backend.test"+ cloud.issuer = "https://backend.test"+ cloud.jwks_uri = "https://backend.test/oauth/jwks.json"+ config.save()++ store = ShowPageStore()+ try:+ page = store.ensure("limited-identity-scenario")+ access = store.get_access(page.session_id)+ assert access is not None+ applied = store.apply_access(+ page.session_id,+ expected_revision=access.revision,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_emails=["[email protected]"],+ )+ assert applied.status == "applied"+ finally:+ store.close()++ client = app.test_client()+ remote_peer = {"REMOTE_ADDR": "203.0.113.44"}+ navigation = client.get(+ f"/p/{page.share_id}/reports/daily?tab=1",+ base_url="https://alex.avibe.bot",+ environ_base=remote_peer,+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ assert navigation.status_code == 302+ authorize_url = urllib.parse.urlsplit(navigation.headers["Location"])+ assert authorize_url.path == (+ "/api/v1/instances/inst_123/show-identity/authorize"+ )+ authorize_query = urllib.parse.parse_qs(authorize_url.query)+ state = authorize_query["state"][0]+ nonce = authorize_query["nonce"][0]++ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ issued_at = int(time.time())+ assertion = jwt.encode(+ {+ "iss": cloud.issuer,+ "aud": f"avibe-show-identity:{cloud.client_id}",+ "sub": "viewer-1",+ "iat": issued_at,+ "exp": issued_at + 300,+ "jti": f"scenario-{time.time_ns()}",+ "nonce": nonce,+ "instance_id": cloud.instance_id,+ "verified_email": "[email protected]",+ },+ private_key,+ algorithm="RS256",+ headers={"typ": "JWT", "kid": "scenario"},+ )++ class ScenarioJwkClient:+ def __init__(self, uri, *, timeout):+ assert uri == cloud.jwks_uri+ assert timeout == 5++ def get_signing_key_from_jwt(self, token):+ assert token == assertion+ return SimpleNamespace(key=private_key.public_key())++ monkeypatch.setattr(show_identity, "PyJWKClient", ScenarioJwkClient)+ form = {"state": state, "assertion": assertion}+ callback = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=remote_peer,+ data=form,+ follow_redirects=False,+ )+ assert callback.status_code == 303+ assert callback.headers["Location"] == f"/p/{page.share_id}/reports/daily?tab=1"+ assert show_identity.show_guest_cookie_name(page.share_id) in callback.headers[+ "Set-Cookie"+ ]++ admitted = client.get(+ f"/p/{page.share_id}/__show/me",+ base_url="https://alex.avibe.bot",+ environ_base=remote_peer,+ )+ assert admitted.status_code == 200+ assert admitted.get_json() == {"authenticated": False, "canAnnotate": False}++ replay = app.test_client().post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base={"REMOTE_ADDR": "203.0.113.45"},+ data=form,+ )+ assert replay.status_code == 400+ assert replay.get_json()["error"] == "replayed_assertion"++class _FakeNextTurnRuntime:def __init__(self):self.refreshed = Falsediff --git a/tests/test_show_identity.py b/tests/test_show_identity.pynew file mode 100644index 000000000..fcbd8bd4f--- /dev/null+++ b/tests/test_show_identity.py@@ -0,0 +1,235 @@+from __future__ import annotations++import time+import threading+from urllib.parse import parse_qs, urlsplit++import jwt+import pytest+from cryptography.hazmat.primitives.asymmetric import rsa++from tests.ui_server_test_helpers import _save_config+from vibe import show_identity+++def _identity_config(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ cloud = config.remote_access.vibe_cloud+ cloud.backend_url = "https://backend.test"+ cloud.issuer = "https://backend.test"+ cloud.jwks_uri = "https://backend.test/oauth/jwks.json"+ config.save()+ return config+++def test_show_identity_state_round_trips_only_for_its_callback_origin(monkeypatch, tmp_path):+ config = _identity_config(monkeypatch, tmp_path)+ authorization_url = show_identity.begin_show_identity_authorization(+ config,+ callback_origin="https://alex.avibe.bot",+ share_id="shared-page",+ return_target="/p/shared-page/reports/daily?tab=1",+ now=100,+ )+ parsed = urlsplit(authorization_url)+ query = parse_qs(parsed.query)++ assert parsed.path == ("/api/v1/instances/inst_123/show-identity/authorize")+ assert query["redirect_uri"] == ["https://alex.avibe.bot/auth/show-identity/callback"]+ state = show_identity.read_show_identity_state(+ config,+ query["state"][0],+ callback_origin="https://alex.avibe.bot",+ now=101,+ )+ assert state.share_id == "shared-page"+ assert state.return_target == "/p/shared-page/reports/daily?tab=1"+ assert query["nonce"] == [state.nonce]++ with pytest.raises(show_identity.ShowIdentityError):+ show_identity.read_show_identity_state(+ config,+ query["state"][0],+ callback_origin="https://other.example",+ now=101,+ )+++def test_show_identity_state_rejects_tampering_and_expiry(monkeypatch, tmp_path):+ config = _identity_config(monkeypatch, tmp_path)+ authorization_url = show_identity.begin_show_identity_authorization(+ config,+ callback_origin="https://alex.avibe.bot",+ share_id="shared-page",+ return_target="/p/shared-page/",+ now=100,+ )+ state = parse_qs(urlsplit(authorization_url).query)["state"][0]++ with pytest.raises(show_identity.ShowIdentityError):+ show_identity.read_show_identity_state(+ config,+ f"{state[:-1]}{'A' if state[-1] != 'A' else 'B'}",+ callback_origin="https://alex.avibe.bot",+ now=101,+ )+ with pytest.raises(show_identity.ShowIdentityError, match="expired_state"):+ show_identity.read_show_identity_state(+ config,+ state,+ callback_origin="https://alex.avibe.bot",+ now=100 + show_identity.STATE_TTL_SECONDS,+ )+++def test_show_identity_assertion_verifies_paired_issuer_instance_and_nonce(+ monkeypatch,+ tmp_path,+):+ config = _identity_config(monkeypatch, tmp_path)+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ issued_at = int(time.time())+ assertion = jwt.encode(+ {+ "iss": "https://backend.test",+ "aud": "avibe-show-identity:vr_client_123",+ "sub": "user-1",+ "iat": issued_at,+ "exp": issued_at + 300,+ "jti": "assertion-1",+ "nonce": "nonce-1",+ "instance_id": "inst_123",+ "verified_email": " [email protected] ",+ },+ private_key,+ algorithm="RS256",+ headers={"typ": "JWT", "kid": "current"},+ )++ class JwkClientStub:+ def __init__(self, uri, *, timeout):+ assert uri == "https://backend.test/oauth/jwks.json"+ assert timeout == 5++ def get_signing_key_from_jwt(self, token):+ assert token == assertion+ return type("SigningKey", (), {"key": private_key.public_key()})()++ monkeypatch.setattr(show_identity, "PyJWKClient", JwkClientStub)++ identity = show_identity.verify_show_identity_assertion(+ config,+ assertion,+ expected_nonce="nonce-1",+ )+ assert identity.subject == "user-1"+ assert identity.normalized_email == "[email protected]"+ assert identity.assertion_id == "assertion-1"+ assert identity.expires_at == issued_at + 300++ with pytest.raises(show_identity.ShowIdentityError, match="invalid_assertion"):+ show_identity.verify_show_identity_assertion(+ config,+ assertion,+ expected_nonce="other-nonce",+ )+++def test_show_identity_assertion_reports_jwks_outage(monkeypatch, tmp_path):+ config = _identity_config(monkeypatch, tmp_path)+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ issued_at = int(time.time())+ assertion = jwt.encode(+ {+ "iss": "https://backend.test",+ "aud": "avibe-show-identity:vr_client_123",+ "sub": "user-1",+ "iat": issued_at,+ "exp": issued_at + 300,+ "jti": "unavailable-assertion",+ "nonce": "nonce-1",+ "instance_id": "inst_123",+ "verified_email": "[email protected]",+ },+ private_key,+ algorithm="RS256",+ headers={"typ": "JWT", "kid": "current"},+ )++ class UnavailableJwkClient:+ def __init__(self, _uri, *, timeout):+ assert timeout == 5++ def get_signing_key_from_jwt(self, _token):+ raise show_identity.PyJWKClientConnectionError("offline")++ monkeypatch.setattr(show_identity, "PyJWKClient", UnavailableJwkClient)++ with pytest.raises(show_identity.ShowIdentityError, match="identity_unavailable"):+ show_identity.verify_show_identity_assertion(+ config,+ assertion,+ expected_nonce="nonce-1",+ )+++def test_verified_show_identity_is_consumed_atomically_once():+ identity = show_identity.VerifiedShowIdentity(+ subject="user-1",+ normalized_email="[email protected]",+ assertion_id=f"atomic-{time.time_ns()}",+ expires_at=int(time.time()) + 300,+ )+ barrier = threading.Barrier(3)+ outcomes: list[str] = []++ def consume():+ barrier.wait()+ try:+ show_identity.consume_verified_show_identity(identity)+ except show_identity.ShowIdentityError as exc:+ outcomes.append(exc.reason)+ else:+ outcomes.append("accepted")++ threads = [threading.Thread(target=consume) for _ in range(2)]+ for thread in threads:+ thread.start()+ barrier.wait()+ for thread in threads:+ thread.join()++ assert sorted(outcomes) == ["accepted", "replayed_assertion"]+++def test_show_guest_lease_is_page_and_share_bound_without_live_membership_state(+ monkeypatch,+ tmp_path,+):+ config = _identity_config(monkeypatch, tmp_path)+ token = show_identity.make_show_guest_lease(+ config,+ page_id="page-1",+ share_id="shared-page",+ normalized_email="[email protected]",+ )+ config.remote_access.vibe_cloud.enabled = False+ config.remote_access.vibe_cloud.backend_url = ""+ config.remote_access.vibe_cloud.issuer = ""+ config.remote_access.vibe_cloud.jwks_uri = ""++ lease = show_identity.read_show_guest_lease(+ config,+ token,+ expected_share_id="shared-page",+ )+ assert lease.page_id == "page-1"+ assert lease.normalized_email == "[email protected]"++ with pytest.raises(show_identity.ShowIdentityError):+ show_identity.read_show_guest_lease(+ config,+ token,+ expected_share_id="other-page",+ )diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 863700d50..170b05bdf 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -40,7 +40,7 @@ from core.show_runtime import (from storage import resource_access_servicefrom tests.ui_server_test_helpers import _mock_interface, _remote_peer, _save_configfrom tests.ui_server_test_helpers import csrf_headers, remote_session_cookie-from vibe import remote_access, ui_server+from vibe import remote_access, show_identity, ui_serverfrom vibe.ui_server import appfrom storage import message_deliveries@@ -450,12 +450,21 @@ def test_public_show_page_serves_from_authed_route(monkeypatch, tmp_path):assert b"Show Page" in response.content-def test_limited_show_page_uses_authed_editor_route_but_not_anonymous_route(+def _configure_show_identity(config):+ cloud = config.remote_access.vibe_cloud+ cloud.backend_url = "https://backend.test"+ cloud.issuer = "https://backend.test"+ cloud.jwks_uri = "https://backend.test/oauth/jwks.json"+ config.save()+++def test_limited_show_page_uses_editor_route_and_redirects_guest_to_identity(monkeypatch,tmp_path,):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ config = _save_config(tmp_path)+ _configure_show_identity(config)share_id = _create_show_page("ses123", "limited")editor = app.test_client().get(@@ -464,14 +473,719 @@ def test_limited_show_page_uses_authed_editor_route_but_not_anonymous_route()shared = app.test_client().get(f"/p/{share_id}/",- base_url="http://127.0.0.1:5123",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,)assert editor.status_code == 200assert b"Show Page" in editor.content- # Limited guest admission belongs to the identity/shared-Runtime delivery- # lane. Until that lands, the anonymous route remains fail-closed.- assert shared.status_code == 404+ assert shared.status_code == 302+ authorization_url = urllib.parse.urlsplit(shared.headers["Location"])+ assert authorization_url.path == (+ "/api/v1/instances/inst_123/show-identity/authorize"+ )+ query = urllib.parse.parse_qs(authorization_url.query)+ assert query["redirect_uri"] == [+ "https://alex.avibe.bot/auth/show-identity/callback"+ ]+ state = show_identity.read_show_identity_state(+ config,+ query["state"][0],+ callback_origin="https://alex.avibe.bot",+ )+ assert state.share_id == share_id+ assert state.return_target == f"/p/{share_id}/"+ assert query["nonce"] == [state.nonce]++ editor_client = app.test_client()+ editor_client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(config, "[email protected]", "owner-1"),+ domain="alex.avibe.bot",+ )+ original_resolve_session = ui_server._resolved_remote_session_payload+ editor_resolution_was_offloaded: list[bool] = []++ def resolve_session_off_loop(config):+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ editor_resolution_was_offloaded.append(True)+ else:+ editor_resolution_was_offloaded.append(False)+ return original_resolve_session(config)++ monkeypatch.setattr(+ ui_server,+ "_resolved_remote_session_payload",+ resolve_session_off_loop,+ )+ editor_shared = editor_client.get(+ f"/p/{share_id}/reports/daily?tab=1",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ assert editor_shared.status_code == 302+ assert editor_shared.headers["Location"] == "/show/ses123/reports/daily?tab=1"+ assert editor_resolution_was_offloaded+ assert all(editor_resolution_was_offloaded)++ editor_client.set_cookie(+ show_identity.show_guest_cookie_name(share_id),+ show_identity.make_show_guest_lease(+ config,+ page_id="ses123",+ share_id=share_id,+ normalized_email="[email protected]",+ ),+ domain="alex.avibe.bot",+ path=show_identity.show_guest_cookie_path(share_id),+ )+ upgraded_editor = editor_client.get(+ f"/p/{share_id}/reports/daily?tab=1",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ assert upgraded_editor.status_code == 302+ assert upgraded_editor.headers["Location"] == "/show/ses123/reports/daily?tab=1"+ assert all(editor_resolution_was_offloaded)++ store = ShowPageStore()+ try:+ access = store.get_access("ses123")+ assert access is not None+ private = store.apply_access(+ "ses123",+ expected_revision=access.revision,+ target_access_mode="private",+ target_share_id=share_id,+ target_emails=[],+ )+ assert private.status == "applied"+ finally:+ store.close()+ private_editor = editor_client.get(+ f"/p/{share_id}/reports/daily?tab=1",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ assert private_editor.status_code == 302+ assert private_editor.headers["Location"] == "/show/ses123/reports/daily?tab=1"++ asset = app.test_client().get(+ f"/p/{share_id}/app.js",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert asset.status_code == 404+++def test_limited_show_callback_maps_outages_and_rechecks_share_binding(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _configure_show_identity(config)+ share_id = _create_show_page("ses123", "limited")+ client = app.test_client()++ login = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ state = urllib.parse.parse_qs(+ urllib.parse.urlsplit(login.headers["Location"]).query+ )["state"][0]+ unavailable = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": state, "error": "identity_unavailable"},+ )+ assert unavailable.status_code == 503+ assert unavailable.get_json()["error"] == "identity_unavailable"++ verifier_login = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ verifier_state = urllib.parse.parse_qs(+ urllib.parse.urlsplit(verifier_login.headers["Location"]).query+ )["state"][0]++ def unavailable_verifier(*_args, **_kwargs):+ raise show_identity.ShowIdentityError("identity_unavailable")++ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ unavailable_verifier,+ )+ verifier_unavailable = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": verifier_state, "assertion": "signed-assertion"},+ )+ assert verifier_unavailable.status_code == 503+ assert verifier_unavailable.get_json()["error"] == "identity_unavailable"++ next_login = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ next_state = urllib.parse.parse_qs(+ urllib.parse.urlsplit(next_login.headers["Location"]).query+ )["state"][0]+ original_get_access = ShowPageStore.get_access++ def get_rotated_access(store, page_id):+ access = original_get_access(store, page_id)+ assert access is not None+ return SimpleNamespace(+ access_mode=access.access_mode,+ share_id="rotated-share",+ normalized_emails=access.normalized_emails,+ )++ monkeypatch.setattr(ShowPageStore, "get_access", get_rotated_access)+ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ lambda *_args, **_kwargs: show_identity.VerifiedShowIdentity(+ subject="viewer-1",+ normalized_email="[email protected]",+ assertion_id="rotated-assertion",+ expires_at=int(ui_server.time.time()) + 300,+ ),+ )+ rotated = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": next_state, "assertion": "signed-assertion"},+ )+ assert rotated.status_code == 403+ assert rotated.get_json()["error"] == "show_access_forbidden"+ assert "Set-Cookie" not in rotated.headers+++def test_limited_show_callback_rejects_offline_page_and_rate_limits_verification(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _configure_show_identity(config)+ share_id = _create_show_page("ses123", "limited")+ client = app.test_client()++ login = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ state = urllib.parse.parse_qs(+ urllib.parse.urlsplit(login.headers["Location"]).query+ )["state"][0]+ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ lambda *_args, **_kwargs: show_identity.VerifiedShowIdentity(+ subject="viewer-1",+ normalized_email="[email protected]",+ assertion_id="offline-assertion",+ expires_at=int(ui_server.time.time()) + 300,+ ),+ )+ store = ShowPageStore()+ try:+ store.update_visibility("ses123", "offline")+ finally:+ store.close()++ offline = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": state, "assertion": "signed-assertion"},+ )+ assert offline.status_code == 403+ assert offline.get_json()["error"] == "show_access_forbidden"+ assert "Set-Cookie" not in offline.headers++ monkeypatch.setattr(ui_server, "_auth_rate_limited", lambda: True)+ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ lambda *_args, **_kwargs: pytest.fail("rate-limited callback verified JWT"),+ )+ limited = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": state, "assertion": "signed-assertion"},+ )+ assert limited.status_code == 429+ assert limited.headers["Cache-Control"] == "no-store"+++def test_show_identity_callback_consumes_assertion_when_page_became_public(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _configure_show_identity(config)+ share_id = _create_show_page("ses123", "limited")+ client = app.test_client()+ login = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ state = urllib.parse.parse_qs(+ urllib.parse.urlsplit(login.headers["Location"]).query+ )["state"][0]+ store = ShowPageStore()+ try:+ access = store.get_access("ses123")+ assert access is not None+ result = store.apply_access(+ "ses123",+ expected_revision=access.revision,+ target_access_mode="public",+ target_share_id=share_id,+ target_emails=[],+ )+ assert result.status == "applied"+ finally:+ store.close()+ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ lambda *_args, **_kwargs: show_identity.VerifiedShowIdentity(+ subject="viewer-1",+ normalized_email="[email protected]",+ assertion_id="became-public-assertion",+ expires_at=int(ui_server.time.time()) + 300,+ ),+ )+ form = {"state": state, "assertion": "signed-assertion"}++ accepted = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data=form,+ follow_redirects=False,+ )+ assert accepted.status_code == 303+ replay = app.test_client().post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data=form,+ )+ assert replay.status_code == 400+ assert replay.get_json()["error"] == "replayed_assertion"+++def test_show_identity_callback_does_not_charge_denied_identity_to_replay_ledger(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _configure_show_identity(config)+ share_id = _create_show_page("ses123", "limited")+ client = app.test_client()+ login = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ state = urllib.parse.parse_qs(+ urllib.parse.urlsplit(login.headers["Location"]).query+ )["state"][0]+ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ lambda *_args, **_kwargs: show_identity.VerifiedShowIdentity(+ subject="unlisted-user",+ normalized_email="[email protected]",+ assertion_id="denied-assertion",+ expires_at=int(ui_server.time.time()) + 300,+ ),+ )+ monkeypatch.setattr(+ show_identity,+ "consume_verified_show_identity",+ lambda _identity: pytest.fail("denied identity consumed replay capacity"),+ )++ denied = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": state, "assertion": "signed-assertion"},+ )++ assert denied.status_code == 403+ assert denied.get_json()["error"] == "show_access_forbidden"+ assert "Set-Cookie" not in denied.headers+++def test_show_identity_callback_body_stops_at_the_streaming_limit():+ class StreamingRequest:+ consumed_chunks = 0++ async def stream(self):+ for chunk in (b"a" * (show_identity.MAX_CALLBACK_BODY_BYTES - 1), b"bb", b"unread"):+ self.consumed_chunks += 1+ yield chunk++ streaming_request = StreamingRequest()++ with pytest.raises(show_identity.ShowIdentityError, match="invalid_callback"):+ asyncio.run(ui_server._read_show_identity_callback_body(streaming_request))+ assert streaming_request.consumed_chunks == 2+++def test_public_show_ignores_an_existing_limited_guest_lease(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _configure_show_identity(config)+ share_id = _create_show_page("ses123", "limited")+ lease = show_identity.make_show_guest_lease(+ config,+ page_id="ses123",+ share_id=share_id,+ normalized_email="[email protected]",+ )+ client = app.test_client()+ client.set_cookie(+ show_identity.show_guest_cookie_name(share_id),+ lease,+ domain="alex.avibe.bot",+ path=show_identity.show_guest_cookie_path(share_id),+ )+ store = ShowPageStore()+ try:+ access = store.get_access("ses123")+ assert access is not None+ result = store.apply_access(+ "ses123",+ expected_revision=access.revision,+ target_access_mode="public",+ target_share_id=share_id,+ target_emails=[],+ )+ assert result.status == "applied"+ finally:+ store.close()++ response = client.get(+ f"/p/{share_id}/app.js",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert response.status_code == 200+ assert response.headers.get("Cache-Control") != "private, no-store"+ assert "Cookie" not in response.headers.get("Vary", "")+++def test_limited_guest_lease_survives_rotation_only_for_that_browser(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _configure_show_identity(config)+ old_share_id = _create_show_page("ses123", "limited")+ lease = show_identity.make_show_guest_lease(+ config,+ page_id="ses123",+ share_id=old_share_id,+ normalized_email="[email protected]",+ )+ admitted = app.test_client()+ admitted.set_cookie(+ show_identity.show_guest_cookie_name(old_share_id),+ lease,+ domain="alex.avibe.bot",+ path=show_identity.show_guest_cookie_path(old_share_id),+ )+ store = ShowPageStore()+ try:+ access = store.get_access("ses123")+ assert access is not None+ result = store.apply_access(+ "ses123",+ expected_revision=access.revision,+ target_access_mode="limited",+ target_share_id="rotated-share",+ target_emails=["[email protected]"],+ )+ assert result.status == "applied"+ finally:+ store.close()++ continuing = admitted.get(+ f"/p/{old_share_id}/app.js",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert continuing.status_code == 200+ fresh_old_link = app.test_client().get(+ f"/p/{old_share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ )+ assert fresh_old_link.status_code == 404+++def test_limited_show_guest_is_admitted_once_and_not_live_revoked(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _configure_show_identity(config)+ share_id = _create_show_page("ses123", "limited")+ manager = _FakeShowRuntimeManager(+ body=(+ b'<!doctype html><html><body><script type="module" '+ b'src="/src/main.tsx"></script></body></html>'+ ),+ bodies_by_path={+ "/sessions/ses123/app/app.js": b"window.guestPage = true;",+ },+ headers_by_path={+ "/sessions/ses123/app/app.js": {+ "content-type": "text/javascript; charset=utf-8"+ },+ "/sessions/ses123/app/api/data": {+ "content-type": "application/json",+ "cache-control": "public, max-age=3600",+ },+ },+ )+ verification_was_offloaded: list[bool] = []++ def verify_identity(*_args, **_kwargs):+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ verification_was_offloaded.append(True)+ else:+ verification_was_offloaded.append(False)+ return show_identity.VerifiedShowIdentity(+ subject="viewer-1",+ normalized_email="[email protected]",+ assertion_id=f"assertion-{_kwargs['expected_nonce']}",+ expires_at=int(ui_server.time.time()) + 300,+ )++ monkeypatch.setattr(+ show_identity,+ "verify_show_identity_assertion",+ verify_identity,+ )+ set_show_runtime_manager_for_tests(manager)+ try:+ client = app.test_client()+ login = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ query = urllib.parse.parse_qs(+ urllib.parse.urlsplit(login.headers["Location"]).query+ )+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _show_page_email_cookie(config),+ domain="alex.avibe.bot",+ )+ callback = client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": query["state"][0], "assertion": "signed-assertion"},+ follow_redirects=False,+ )+ assert callback.status_code == 303+ assert verification_was_offloaded == [True]+ assert callback.headers["Location"] == f"/p/{share_id}/"+ set_cookie = callback.headers["Set-Cookie"]+ assert "HttpOnly" in set_cookie+ assert "Secure" in set_cookie+ assert "SameSite=Lax" in set_cookie+ assert "Expires=" not in set_cookie+ assert "Max-Age=" not in set_cookie+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ "",+ domain="alex.avibe.bot",+ )++ replay = app.test_client().post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={"state": query["state"][0], "assertion": "signed-assertion"},+ )+ assert replay.status_code == 400+ assert replay.get_json()["error"] == "replayed_assertion"+ assert show_identity.show_guest_cookie_name(share_id) not in replay.headers.get(+ "Set-Cookie", ""+ )++ page = client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ )+ assert page.status_code == 200+ assert page.headers["Cache-Control"] == "private, no-store"+ assert page.headers["Content-Security-Policy"] == "frame-ancestors 'none'"+ assert b'"authenticated":false' in page.content+ assert b"__show/annotation.js" not in page.content++ api_response = client.post(+ f"/p/{share_id}/api/data",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers=csrf_headers(client, "https://alex.avibe.bot"),+ json={"action": "refresh"},+ )+ assert api_response.status_code == 200+ assert api_response.headers["Cache-Control"] == "private, no-store"+ assert "Cookie" in api_response.headers["Vary"]++ events = client.get(+ f"/p/{share_id}/__show/events",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert events.status_code == 404++ store = ShowPageStore()+ try:+ access = store.get_access("ses123")+ assert access is not None+ removed = store.apply_access(+ "ses123",+ expected_revision=access.revision,+ target_access_mode="limited",+ target_share_id=share_id,+ target_emails=["[email protected]"],+ )+ assert removed.status == "applied"+ finally:+ store.close()++ existing_asset = client.get(+ f"/p/{share_id}/app.js",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert existing_asset.status_code == 200++ fresh_client = app.test_client()+ fresh_login = fresh_client.get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ fresh_query = urllib.parse.parse_qs(+ urllib.parse.urlsplit(fresh_login.headers["Location"]).query+ )+ denied = fresh_client.post(+ show_identity.CALLBACK_PATH,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ data={+ "state": fresh_query["state"][0],+ "assertion": "signed-assertion",+ },+ )+ assert denied.status_code == 403++ store = ShowPageStore()+ try:+ access = store.get_access("ses123")+ assert access is not None+ made_private = store.apply_access(+ "ses123",+ expected_revision=access.revision,+ target_access_mode="private",+ target_share_id=share_id,+ target_emails=[],+ )+ assert made_private.status == "applied"+ finally:+ store.close()++ still_open = client.get(+ f"/p/{share_id}/app.js",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert still_open.status_code == 200+ new_visit = app.test_client().get(+ f"/p/{share_id}/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ )+ assert new_visit.status_code == 404++ store = ShowPageStore()+ try:+ offline = store.update_visibility("ses123", "offline")+ assert offline.visibility == "offline"+ finally:+ store.close()+ stopped = client.get(+ f"/p/{share_id}/app.js",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert stopped.status_code == 401+ finally:+ set_show_runtime_manager_for_tests(None)def test_public_show_page_still_requires_remote_login(monkeypatch, tmp_path):diff --git a/vibe/show_identity.py b/vibe/show_identity.pynew file mode 100644index 000000000..f339815fb--- /dev/null+++ b/vibe/show_identity.py@@ -0,0 +1,445 @@+from __future__ import annotations++import base64+import hashlib+import hmac+import json+import secrets+import threading+import time+from dataclasses import dataclass+from typing import Any+from urllib.parse import quote, urlencode, urlsplit++import jwt+from jwt import PyJWKClient+from jwt.exceptions import PyJWKClientConnectionError++from config.v2_config import V2Config+from core.show_pages import normalize_show_access_email, validate_share_id+++CALLBACK_PATH = "/auth/show-identity/callback"+STATE_TTL_SECONDS = 10 * 60+ASSERTION_CLOCK_LEEWAY_SECONDS = 60+ASSERTION_MAX_TTL_SECONDS = 10 * 60+MAX_STATE_BYTES = 4096+MAX_ASSERTION_BYTES = 16 * 1024+MAX_CALLBACK_BODY_BYTES = 24 * 1024+MAX_CONSUMED_ASSERTIONS = 4096+_STATE_PREFIX = "vsi1"+_LEASE_PREFIX = "vsl1"+_STATE_PROCESS_SECRET = secrets.token_bytes(32)+_CONSUMED_ASSERTIONS_LOCK = threading.Lock()+_CONSUMED_ASSERTIONS: dict[str, int] = {}+++class ShowIdentityError(ValueError):+ def __init__(self, reason: str):+ super().__init__(reason)+ self.reason = reason+++@dataclass(frozen=True)+class ShowIdentityState:+ share_id: str+ return_target: str+ nonce: str+ callback_origin: str+++@dataclass(frozen=True)+class VerifiedShowIdentity:+ subject: str+ normalized_email: str+ assertion_id: str+ expires_at: int+++@dataclass(frozen=True)+class ShowGuestLease:+ page_id: str+ share_id: str+ normalized_email: str+++def _b64url_encode(value: bytes) -> str:+ return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii")+++def _b64url_decode(value: str) -> bytes:+ if not value or any(+ character not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" for character in value+ ):+ raise ShowIdentityError("invalid_token")+ try:+ return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))+ except Exception as exc:+ raise ShowIdentityError("invalid_token") from exc+++def _signature(secret: str, prefix: str, payload: str) -> str:+ return _b64url_encode(+ hmac.new(+ secret.encode("utf-8"),+ f"{prefix}.{payload}".encode("ascii"),+ hashlib.sha256,+ ).digest()+ )+++def _state_secret(secret: str) -> str:+ return hmac.new(+ secret.encode("utf-8"),+ _STATE_PROCESS_SECRET,+ hashlib.sha256,+ ).hexdigest()+++def _encode_signed_payload(secret: str, prefix: str, payload: dict[str, Any]) -> str:+ encoded = _b64url_encode(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8"))+ return f"{prefix}.{encoded}.{_signature(secret, prefix, encoded)}"+++def _decode_signed_payload(+ secret: str,+ prefix: str,+ token: str | None,+ *,+ max_bytes: int,+) -> dict[str, Any]:+ if not isinstance(token, str) or len(token.encode("utf-8")) > max_bytes:+ raise ShowIdentityError("invalid_token")+ try:+ token_prefix, encoded, signature = token.split(".", 2)+ except ValueError as exc:+ raise ShowIdentityError("invalid_token") from exc+ expected = _signature(secret, prefix, encoded)+ if token_prefix != prefix or not hmac.compare_digest(signature, expected):+ raise ShowIdentityError("invalid_token")+ try:+ payload = json.loads(_b64url_decode(encoded))+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ShowIdentityError("invalid_token") from exc+ if not isinstance(payload, dict):+ raise ShowIdentityError("invalid_token")+ return payload+++def _cloud(config: V2Config):+ cloud = config.remote_access.vibe_cloud+ required = (+ cloud.enabled,+ cloud.backend_url,+ cloud.instance_id,+ cloud.client_id,+ cloud.issuer,+ cloud.jwks_uri,+ cloud.session_secret,+ )+ if not all(required):+ raise ShowIdentityError("identity_unavailable")+ return cloud+++def _lease_secret(config: V2Config) -> str:+ secret = config.remote_access.vibe_cloud.session_secret+ if not isinstance(secret, str) or not secret:+ raise ShowIdentityError("identity_unavailable")+ return secret+++def _normalize_origin(origin: str) -> str:+ try:+ parsed = urlsplit(origin)+ port = parsed.port+ except ValueError as exc:+ raise ShowIdentityError("invalid_callback_origin") from exc+ if (+ parsed.scheme != "https"+ or not parsed.hostname+ or parsed.username is not None+ or parsed.password is not None+ or parsed.path not in {"", "/"}+ or parsed.query+ or parsed.fragment+ ):+ raise ShowIdentityError("invalid_callback_origin")+ host = parsed.hostname.lower()+ if ":" in host:+ host = f"[{host}]"+ return f"https://{host}{f':{port}' if port is not None and port != 443 else ''}"+++def _validate_return_target(share_id: str, return_target: str) -> str:+ if not isinstance(return_target, str) or len(return_target) > 2048:+ raise ShowIdentityError("invalid_return_target")+ parsed = urlsplit(return_target)+ prefix = f"/p/{quote(share_id, safe='')}/"+ if (+ parsed.scheme+ or parsed.netloc+ or parsed.fragment+ or not (parsed.path == prefix or parsed.path.startswith(prefix))+ ):+ raise ShowIdentityError("invalid_return_target")+ return return_target+++def begin_show_identity_authorization(+ config: V2Config,+ *,+ callback_origin: str,+ share_id: str,+ return_target: str,+ now: int | None = None,+) -> str:+ cloud = _cloud(config)+ share_id = validate_share_id(share_id)+ callback_origin = _normalize_origin(callback_origin)+ return_target = _validate_return_target(share_id, return_target)+ issued_at = int(time.time()) if now is None else int(now)+ nonce = secrets.token_urlsafe(32)+ state = _encode_signed_payload(+ _state_secret(cloud.session_secret),+ _STATE_PREFIX,+ {+ "v": 1,+ "share_id": share_id,+ "return_target": return_target,+ "nonce": nonce,+ "callback_origin": callback_origin,+ "exp": issued_at + STATE_TTL_SECONDS,+ },+ )+ backend = cloud.backend_url.rstrip("/")+ endpoint = f"{backend}/api/v1/instances/{quote(cloud.instance_id, safe='')}/show-identity/authorize"+ query = urlencode(+ {+ "state": state,+ "nonce": nonce,+ "redirect_uri": f"{callback_origin}{CALLBACK_PATH}",+ }+ )+ return f"{endpoint}?{query}"+++def read_show_identity_state(+ config: V2Config,+ token: str | None,+ *,+ callback_origin: str,+ now: int | None = None,+) -> ShowIdentityState:+ cloud = _cloud(config)+ payload = _decode_signed_payload(+ _state_secret(cloud.session_secret),+ _STATE_PREFIX,+ token,+ max_bytes=MAX_STATE_BYTES,+ )+ if set(payload) != {+ "v",+ "share_id",+ "return_target",+ "nonce",+ "callback_origin",+ "exp",+ }:+ raise ShowIdentityError("invalid_state")+ if payload.get("v") != 1 or type(payload.get("exp")) is not int:+ raise ShowIdentityError("invalid_state")+ current_time = int(time.time()) if now is None else int(now)+ if payload["exp"] <= current_time:+ raise ShowIdentityError("expired_state")+ raw_share_id = payload.get("share_id")+ if not isinstance(raw_share_id, str):+ raise ShowIdentityError("invalid_state")+ try:+ share_id = validate_share_id(raw_share_id)+ except Exception as exc:+ raise ShowIdentityError("invalid_state") from exc+ nonce = payload.get("nonce")+ signed_origin = payload.get("callback_origin")+ if not isinstance(nonce, str) or not nonce or len(nonce) > 256:+ raise ShowIdentityError("invalid_state")+ if not isinstance(signed_origin, str) or not hmac.compare_digest(+ signed_origin,+ _normalize_origin(callback_origin),+ ):+ raise ShowIdentityError("invalid_callback_origin")+ return ShowIdentityState(+ share_id=share_id,+ return_target=_validate_return_target(share_id, payload.get("return_target")),+ nonce=nonce,+ callback_origin=signed_origin,+ )+++def verify_show_identity_assertion(+ config: V2Config,+ token: str | None,+ *,+ expected_nonce: str,+) -> VerifiedShowIdentity:+ cloud = _cloud(config)+ if not isinstance(token, str) or not token or len(token.encode("utf-8")) > MAX_ASSERTION_BYTES:+ raise ShowIdentityError("invalid_assertion")+ try:+ header = jwt.get_unverified_header(token)+ if (+ header.get("alg") != "RS256"+ or header.get("typ") != "JWT"+ or not isinstance(header.get("kid"), str)+ or not header["kid"]+ ):+ raise ShowIdentityError("invalid_assertion")+ signing_key = PyJWKClient(cloud.jwks_uri, timeout=5).get_signing_key_from_jwt(token)+ claims = jwt.decode(+ token,+ signing_key.key,+ algorithms=["RS256"],+ audience=f"avibe-show-identity:{cloud.client_id}",+ issuer=cloud.issuer,+ leeway=ASSERTION_CLOCK_LEEWAY_SECONDS,+ options={+ "require": [+ "iss",+ "aud",+ "sub",+ "iat",+ "exp",+ "jti",+ "nonce",+ "instance_id",+ "verified_email",+ ]+ },+ )+ except ShowIdentityError:+ raise+ except PyJWKClientConnectionError as exc:+ raise ShowIdentityError("identity_unavailable") from exc+ except Exception as exc:+ raise ShowIdentityError("invalid_assertion") from exc++ string_claims = ("sub", "jti", "nonce", "instance_id", "verified_email")+ if any(not isinstance(claims.get(name), str) or not claims[name] for name in string_claims):+ raise ShowIdentityError("invalid_assertion")+ if type(claims.get("iat")) is not int or type(claims.get("exp")) is not int:+ raise ShowIdentityError("invalid_assertion")+ if claims["exp"] <= claims["iat"] or claims["exp"] - claims["iat"] > ASSERTION_MAX_TTL_SECONDS:+ raise ShowIdentityError("invalid_assertion")+ if claims["nonce"] != expected_nonce or claims["instance_id"] != cloud.instance_id:+ raise ShowIdentityError("invalid_assertion")+ try:+ normalized_email = normalize_show_access_email(claims["verified_email"])+ except Exception as exc:+ raise ShowIdentityError("invalid_assertion") from exc+ return VerifiedShowIdentity(+ subject=claims["sub"],+ normalized_email=normalized_email,+ assertion_id=claims["jti"],+ expires_at=claims["exp"],+ )+++def consume_verified_show_identity(+ identity: VerifiedShowIdentity,+ *,+ now: int | None = None,+) -> None:+ current_time = int(time.time()) if now is None else int(now)+ retain_until = identity.expires_at + ASSERTION_CLOCK_LEEWAY_SECONDS+ with _CONSUMED_ASSERTIONS_LOCK:+ expired = [+ assertion_id for assertion_id, expires_at in _CONSUMED_ASSERTIONS.items() if expires_at <= current_time+ ]+ for assertion_id in expired:+ _CONSUMED_ASSERTIONS.pop(assertion_id, None)+ if identity.assertion_id in _CONSUMED_ASSERTIONS:+ raise ShowIdentityError("replayed_assertion")+ if len(_CONSUMED_ASSERTIONS) >= MAX_CONSUMED_ASSERTIONS:+ raise ShowIdentityError("identity_unavailable")+ _CONSUMED_ASSERTIONS[identity.assertion_id] = retain_until+++def show_guest_cookie_name(share_id: str) -> str:+ share_id = validate_share_id(share_id)+ suffix = hashlib.sha256(share_id.encode("utf-8")).hexdigest()[:20]+ return f"__Secure-vibe_show_guest_{suffix}"+++def show_guest_cookie_path(share_id: str) -> str:+ return f"/p/{quote(validate_share_id(share_id), safe='')}"+++def make_show_guest_lease(+ config: V2Config,+ *,+ page_id: str,+ share_id: str,+ normalized_email: str,+) -> str:+ # Deliberately a browser-session lease: access changes govern new+ # admissions without interrupting a page the user already opened.+ return _encode_signed_payload(+ _lease_secret(config),+ _LEASE_PREFIX,+ {+ "v": 1,+ "page_id": page_id,+ "share_id": validate_share_id(share_id),+ "normalized_email": normalize_show_access_email(normalized_email),+ "lease_id": secrets.token_urlsafe(18),+ },+ )+++def read_show_guest_lease(+ config: V2Config,+ token: str | None,+ *,+ expected_share_id: str,+) -> ShowGuestLease:+ payload = _decode_signed_payload(+ _lease_secret(config),+ _LEASE_PREFIX,+ token,+ max_bytes=MAX_STATE_BYTES,+ )+ if set(payload) != {+ "v",+ "page_id",+ "share_id",+ "normalized_email",+ "lease_id",+ }:+ raise ShowIdentityError("invalid_lease")+ if payload.get("v") != 1:+ raise ShowIdentityError("invalid_lease")+ page_id = payload.get("page_id")+ share_id = payload.get("share_id")+ lease_id = payload.get("lease_id")+ try:+ expected_share_id = validate_share_id(expected_share_id)+ except Exception as exc:+ raise ShowIdentityError("invalid_lease") from exc+ if (+ not isinstance(page_id, str)+ or not page_id+ or not isinstance(share_id, str)+ or share_id != expected_share_id+ or not isinstance(lease_id, str)+ or not lease_id+ ):+ raise ShowIdentityError("invalid_lease")+ try:+ normalized_email = normalize_show_access_email(payload.get("normalized_email"))+ except Exception as exc:+ raise ShowIdentityError("invalid_lease") from exc+ return ShowGuestLease(+ page_id=page_id,+ share_id=share_id,+ normalized_email=normalized_email,+ )diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 72c562d4a..71d001bce 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -576,7 +576,12 @@ def _trusted_public_origin_local_request(config: V2Config | None) -> bool:def _is_mutation_guard_exempt() -> bool:- if request.path in {"/auth/callback", "/auth/organization/callback", "/auth/organization/start"}:+ if request.path in {+ "/auth/callback",+ "/auth/organization/callback",+ "/auth/organization/start",+ "/auth/show-identity/callback",+ }:return Trueif _is_cli_show_event_request() or _is_cli_session_activity_request():return True@@ -1565,6 +1570,7 @@ def _remote_auth_exempt_path() -> bool:or path == "/auth/callback"or path == "/auth/organization/callback"or path == "/auth/organization/start"+ or path == "/auth/show-identity/callback"or path == "/auth/logout"or path == "/api/session"or path == "/api/cloud/token"@@ -2430,6 +2436,7 @@ def enforce_show_page_email_scope():_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH,_SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH,"/auth/callback",+ "/auth/show-identity/callback","/auth/logout","/health",}@@ -13259,18 +13266,41 @@ def _show_annotation_capability(}-def _show_request_author(*, public: bool = False) -> dict[str, str] | None:- from vibe import remote_access- from vibe.authorization import context_from_session_payload+def _show_public_editor_context():+ from vibe.authorization import context_from_session_payload, instance_owner_context- if not public:- context = getattr(g, "authorization_context", None)+ config = _load_remote_access_config()+ if config is not None:+ session = _resolved_remote_session_payload(config)+ context = context_from_session_payload(session) if session is not None else Noneif context is not None:- if not context.has_role("editor"):- return None- if context.is_remote:- return {"kind": "user", "email": context.email} if context.email else None- return {"kind": "local"}+ return context if context.has_role("editor") else None+ if config.remote_access.vibe_cloud.enabled:+ return None+ if not (_is_local_request(config) or _is_loopback_origin_proxy_request()):+ return None+ return instance_owner_context()+++async def _show_public_request_author() -> dict[str, str] | None:+ context = await asyncio.to_thread(_show_public_editor_context)+ if context is None:+ return None+ if context.is_remote:+ return {"kind": "user", "email": context.email} if context.email else None+ return {"kind": "local"}+++def _show_request_author() -> dict[str, str] | None:+ from vibe.authorization import context_from_session_payload++ context = getattr(g, "authorization_context", None)+ if context is not None:+ if not context.has_role("editor"):+ return None+ if context.is_remote:+ return {"kind": "user", "email": context.email} if context.email else None+ return {"kind": "local"}config = _load_remote_access_config()if config is not None:@@ -13286,12 +13316,6 @@ def _show_request_author(*, public: bool = False) -> dict[str, str] | None:return {"kind": "user", "email": email}return None- cloud = config.remote_access.vibe_cloud- if public and cloud.enabled:- return None-- if public and not (_is_local_request(config) or _is_loopback_origin_proxy_request()):- return Nonereturn {"kind": "local"}@@ -14232,6 +14256,7 @@ async def _show_page_runtime_response(inject_show_config: bool = False,show_authenticated: bool = False,show_config_session_id: str | None = None,+ include_annotation_bootstrap: bool = True,):from core.show_runtime import (ShowRuntimeContext,@@ -14334,6 +14359,7 @@ async def _show_page_runtime_response(base_path=base_path,authenticated=show_authenticated,include_write_token=external_prefix is None and show_authenticated,+ include_annotation_bootstrap=include_annotation_bootstrap,)if external_prefix:response_headers["Referrer-Policy"] = "same-origin"@@ -14678,6 +14704,7 @@ def _inject_show_runtime_config(base_path: str,authenticated: bool,include_write_token: bool,+ include_annotation_bootstrap: bool = True,) -> bytes:try:html = content.decode("utf-8")@@ -14689,7 +14716,11 @@ def _inject_show_runtime_config(authenticated=authenticated,include_write_token=include_write_token,)- bootstrap = f'<script type="module" src="{base_path}__show/annotation.js"></script>'+ bootstrap = (+ f'<script type="module" src="{base_path}__show/annotation.js"></script>'+ if include_annotation_bootstrap+ else ""+ )module_match = _SHOW_RUNTIME_MODULE_SCRIPT_RE.search(html)if module_match:html = f"{html[: module_match.start()]}{script}\n {html[module_match.start() :]}"@@ -14699,12 +14730,13 @@ def _inject_show_runtime_config(html = html.replace("</body>", f"{script}\n </body>", 1)else:html = f"{script}\n{html}"- if "</body>" in html:- html = html.replace("</body>", f"{bootstrap}\n </body>", 1)- elif "</html>" in html:- html = html.replace("</html>", f"{bootstrap}\n</html>", 1)- else:- html = f"{html}\n{bootstrap}"+ if bootstrap:+ if "</body>" in html:+ html = html.replace("</body>", f"{bootstrap}\n </body>", 1)+ elif "</html>" in html:+ html = html.replace("</html>", f"{bootstrap}\n</html>", 1)+ else:+ html = f"{html}\n{bootstrap}"return html.encode("utf-8")@@ -14889,16 +14921,212 @@ async def serve_private_show_page(session_id, asset_path):store.close()+def _show_identity_error_response(error: str, status: int):+ response = jsonify({"ok": False, "error": error})+ response.status_code = status+ response.headers["Cache-Control"] = "private, no-store"+ response.headers["Referrer-Policy"] = "no-referrer"+ return response+++def _show_identity_error_status(error: str, *, default: int = 400) -> int:+ if error == "identity_unavailable":+ return 503+ if error == "identity_not_verified":+ return 403+ return default+++async def _read_show_identity_callback_body(+ starlette_request: FastAPIRequest,+) -> bytes:+ from vibe.show_identity import MAX_CALLBACK_BODY_BYTES, ShowIdentityError++ body = bytearray()+ async for chunk in starlette_request.stream():+ if len(body) + len(chunk) > MAX_CALLBACK_BODY_BYTES:+ raise ShowIdentityError("invalid_callback")+ body.extend(chunk)+ return bytes(body)+++async def _show_identity_callback_fields() -> dict[str, str]:+ from vibe.show_identity import MAX_CALLBACK_BODY_BYTES, ShowIdentityError++ content_type = request.headers.get("content-type", "")+ if content_type.split(";", 1)[0].strip().lower() != "application/x-www-form-urlencoded":+ raise ShowIdentityError("invalid_callback")+ content_length = request.headers.get("content-length")+ if content_length:+ try:+ parsed_content_length = int(content_length)+ if parsed_content_length < 0 or parsed_content_length > MAX_CALLBACK_BODY_BYTES:+ raise ShowIdentityError("invalid_callback")+ except ValueError as exc:+ raise ShowIdentityError("invalid_callback") from exc+ body = await _read_show_identity_callback_body(request._request)+ try:+ pairs = parse_qsl(+ body.decode("utf-8"),+ keep_blank_values=True,+ strict_parsing=True,+ )+ except (UnicodeDecodeError, ValueError) as exc:+ raise ShowIdentityError("invalid_callback") from exc+ fields: dict[str, str] = {}+ for key, value in pairs:+ if key in fields:+ raise ShowIdentityError("invalid_callback")+ fields[key] = value+ if set(fields) not in ({"state", "assertion"}, {"state", "error"}):+ raise ShowIdentityError("invalid_callback")+ if any(not value for value in fields.values()):+ raise ShowIdentityError("invalid_callback")+ return fields+++def _show_guest_lease(config: V2Config | None, share_id: str):+ from core.show_pages import ShowPageError+ from vibe import show_identity++ if config is None:+ return None+ try:+ return show_identity.read_show_guest_lease(+ config,+ request.cookies.get(show_identity.show_guest_cookie_name(share_id)),+ expected_share_id=share_id,+ )+ except (ShowPageError, show_identity.ShowIdentityError):+ return None+++def _with_limited_show_policy(response: Response) -> Response:+ response.headers["Cache-Control"] = "private, no-store"+ vary = response.headers.get("Vary", "")+ vary_values = {value.strip() for value in vary.split(",") if value.strip()}+ vary_values.add("Cookie")+ response.headers["Vary"] = ", ".join(sorted(vary_values))+ response.headers["X-Content-Type-Options"] = "nosniff"+ response.headers["Referrer-Policy"] = "no-referrer"+ response.headers["Content-Security-Policy"] = "frame-ancestors 'none'"+ return response++[email protected]("/auth/show-identity/callback", methods=["POST"])+async def complete_show_identity_login():+ from core.show_pages import ShowPageStore+ from vibe import show_identity++ if _auth_rate_limited():+ return _auth_rate_limit_response()+ config = _load_remote_access_config()+ if config is None:+ return _show_identity_error_response("identity_unavailable", 503)+ try:+ fields = await _show_identity_callback_fields()+ state = show_identity.read_show_identity_state(+ config,+ fields.get("state"),+ callback_origin=_current_origin(),+ )+ if "error" in fields:+ if fields["error"] not in {"identity_not_verified", "identity_unavailable"}:+ raise show_identity.ShowIdentityError("invalid_callback")+ return _show_identity_error_response(+ fields["error"],+ _show_identity_error_status(fields["error"]),+ )+ identity = await asyncio.to_thread(+ show_identity.verify_show_identity_assertion,+ config,+ fields.get("assertion"),+ expected_nonce=state.nonce,+ )+ except show_identity.ShowIdentityError as exc:+ return _show_identity_error_response(+ exc.reason,+ _show_identity_error_status(exc.reason),+ )+ except Exception:+ logger.warning("Show identity callback failed", exc_info=True)+ return _show_identity_error_response("identity_unavailable", 503)++ store = ShowPageStore()+ try:+ page = store.get_by_share_id(state.share_id)+ if page is None:+ return _show_identity_error_response("not_found", 404)+ if page.visibility == "offline":+ return _show_identity_error_response("show_access_forbidden", 403)+ access = store.get_access(page.session_id)+ if access is None:+ return _show_identity_error_response("not_found", 404)+ if access.access_mode == "public":+ try:+ show_identity.consume_verified_show_identity(identity)+ except show_identity.ShowIdentityError as exc:+ return _show_identity_error_response(+ exc.reason,+ _show_identity_error_status(exc.reason),+ )+ return redirect(state.return_target, code=303)+ if (+ access.access_mode != "limited"+ or access.share_id != state.share_id+ or identity.normalized_email not in access.normalized_emails+ ):+ return _show_identity_error_response("show_access_forbidden", 403)++ try:+ show_identity.consume_verified_show_identity(identity)+ except show_identity.ShowIdentityError as exc:+ return _show_identity_error_response(+ exc.reason,+ _show_identity_error_status(exc.reason),+ )++ # This browser-session lease intentionally has no live revision check:+ # membership changes affect new admissions, not a page already opened.+ lease = show_identity.make_show_guest_lease(+ config,+ page_id=page.session_id,+ share_id=state.share_id,+ normalized_email=identity.normalized_email,+ )+ response = redirect(state.return_target, code=303)+ response.set_cookie(+ show_identity.show_guest_cookie_name(state.share_id),+ lease,+ httponly=True,+ secure=True,+ samesite="Lax",+ path=show_identity.show_guest_cookie_path(state.share_id),+ )+ response.headers["Cache-Control"] = "private, no-store"+ response.headers["Referrer-Policy"] = "no-referrer"+ return response+ finally:+ store.close()++@app.route("/p/<share_id>")def redirect_public_show_page_to_canonical_path(share_id):from core.show_pages import ShowPageStore+ config = _load_remote_access_config()+ lease = _show_guest_lease(config, share_id)store = ShowPageStore()try:page = store.get_by_share_id(share_id)+ if page is None and lease is not None:+ # A lease preserves an already-admitted browser across audience and+ # share-link changes. New visitors cannot resolve the retired link;+ # explicit offline is the only immediate availability withdrawal.+ page = store.get(lease.page_id)if page is None:return _show_page_not_found_response()- if page.visibility not in {"public", "offline"}:+ if lease is None and page.visibility not in {"public", "limited", "offline"}:return _show_page_not_found_response()return redirect(f"/p/{quote(share_id, safe='')}/")finally:@@ -14915,16 +15143,68 @@ def redirect_public_show_page_to_canonical_path(share_id):methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],)async def serve_public_show_page(share_id, asset_path):- from core.show_pages import ShowPageStore, ensure_show_page_dir+ from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir+ from vibe import show_identity+ config = _load_remote_access_config()+ lease = _show_guest_lease(config, share_id)store = ShowPageStore()try:page = store.get_by_share_id(share_id)+ if page is None and lease is not None:+ page = store.get(lease.page_id)if page is None:return _show_page_not_found_response()+ limited_guest = (+ lease is not None+ and lease.page_id == page.session_id+ and page.visibility != "public"+ )if page.visibility == "offline":return _show_page_offline_response()- if page.visibility != "public":+ is_spa_navigation = _is_show_page_spa_route_request(+ asset_path,+ request._request,+ )+ if page.visibility != "public" and is_spa_navigation:+ editor_context = await asyncio.to_thread(_show_public_editor_context)+ if editor_context is not None:+ try:+ store.require_access(+ page.session_id,+ user_context=editor_context,+ )+ except ShowPageError:+ pass+ else:+ private_target = f"/show/{quote(page.session_id, safe='')}/"+ if asset_path:+ private_target += quote(asset_path.lstrip("/"), safe="/@:-._~")+ query = urlsplit(request.full_path).query+ if query:+ private_target = f"{private_target}?{query}"+ return redirect(private_target)+ if page.visibility == "limited":+ if not limited_guest:+ if request.method != "GET" or not is_spa_navigation:+ return _show_page_not_found_response()+ if config is None:+ return _show_identity_error_response("identity_unavailable", 503)+ return_target = request.full_path if request.query_string else request.path+ try:+ authorization_url = show_identity.begin_show_identity_authorization(+ config,+ callback_origin=_current_origin(),+ share_id=share_id,+ return_target=return_target,+ )+ except show_identity.ShowIdentityError:+ return _show_identity_error_response("identity_unavailable", 503)+ response = redirect(authorization_url)+ response.headers["Cache-Control"] = "private, no-store"+ response.headers["Referrer-Policy"] = "no-referrer"+ return response+ if not limited_guest and page.visibility != "public":return _show_page_not_found_response()if _is_show_page_runtime_denied_path(asset_path,@@ -14935,20 +15215,23 @@ async def serve_public_show_page(share_id, asset_path):if asset_path.strip("/") == "__show/me":if request.method not in {"GET", "HEAD"}:return jsonify({"ok": False, "code": "method_not_allowed"}), 405- author = _show_request_author(public=True)+ author = None if limited_guest else await _show_public_request_author()can_annotate = _show_annotation_capability(author=author,page=page,public_share_id=share_id,- )- return _show_me_response(+ ) if not limited_guest else False+ response = _show_me_response(author,can_annotate=can_annotate,write_token=(show_public_event_write_token(share_id, page.session_id) if can_annotate else None),)+ return _with_limited_show_policy(response) if limited_guest else responseif asset_path.strip("/").startswith("__show/media/"):+ if limited_guest:+ return _show_page_file_not_found_response()if request.method not in {"GET", "HEAD"}:return jsonify({"ok": False, "code": "method_not_allowed"}), 405token = asset_path.strip("/").removeprefix("__show/media/")@@ -14961,6 +15244,8 @@ async def serve_public_show_page(share_id, asset_path):public_show_page=True,)if asset_path.strip("/") in {"__show/events", "__events"}:+ if limited_guest:+ return _show_page_file_not_found_response()if request.method == "GET":return await _show_events_response(page.session_id,@@ -14969,7 +15254,7 @@ async def serve_public_show_page(share_id, asset_path):)if request.method != "POST":return jsonify({"ok": False, "code": "method_not_allowed"}), 405- author = _show_request_author(public=True)+ author = await _show_public_request_author()if author is None:return jsonify({"ok": False, "code": "public_show_events_login_required"}), 403can_annotate = _show_annotation_capability(@@ -14998,19 +15283,25 @@ async def serve_public_show_page(share_id, asset_path):if request.method in {"GET", "HEAD"}:if shim_response := _show_runtime_public_client_shim_response(asset_path):return shim_response+ if limited_guest and _is_show_annotation_asset(asset_path):+ return _show_page_file_not_found_response()page_dir = ensure_show_page_dir(page.session_id)response = Noneif request.method in {"GET", "HEAD"} or _is_show_api_asset(asset_path):try:starlette_request = request._request+ show_authenticated = False+ if not limited_guest:+ show_authenticated = await _show_public_request_author() is not Noneresponse = await _show_page_runtime_response(page.session_id,asset_path,starlette_request,external_prefix=f"/p/{quote(share_id, safe='')}",inject_show_config=request.method == "GET" and not _is_show_api_asset(asset_path),- show_authenticated=_show_request_author(public=True) is not None,+ show_authenticated=show_authenticated,show_config_session_id=share_id,+ include_annotation_bootstrap=not limited_guest,)except Exception:if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):@@ -15027,6 +15318,8 @@ async def serve_public_show_page(share_id, asset_path):logger.debug("Show runtime unavailable; serving static public Show Page", exc_info=True)if response is None:response = _show_page_file_response(page_dir, asset_path)+ if limited_guest:+ return _with_limited_show_policy(response)if request.method in {"GET", "HEAD"}:if _is_show_runtime_immutable_asset_path(asset_path):return response