Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat: scope email access to one Show Page

Max6a6eecf3c469
diff --git a/docs/plans/show-page-email-access.md b/docs/plans/show-page-email-access.md
new file mode 100644
index 000000000..9da002d6b
--- /dev/null
+++ b/docs/plans/show-page-email-access.md
@@ -0,0 +1,45 @@
+# ShowPage Email Access
+
+## Goal
+
+Allow a ShowPage owner to grant exact email addresses access to one ShowPage.
+Organization ShowPages retain the same email audience and additionally support
+the whole Organization or selected Organization groups.
+
+Anonymous Public links remain an independent sharing switch.
+
+## Authorization Contract
+
+- A grant is keyed by `instance_id + show_page_id + normalized_email`.
+- The OIDC request carries the target `show_page_id`.
+- A user admitted only by that grant receives `vibe_instance_access_source =
+ show_page_email`, `vibe_instance_role = viewer`, and a signed
+ `vibe_show_page_id` claim.
+- Existing Instance owner, email, domain, group, and public-instance access wins
+ before the ShowPage-only grant so existing users keep their broader access.
+- A `show_page_email` browser session may serve only the exact
+ `/show/<vibe_show_page_id>` route subtree and required public static assets.
+ Workbench, Chat, other Sessions, Agents, files, Cloud capabilities, APIs, and
+ other ShowPages fail closed.
+- ShowPage resource authorization independently requires the requested resource
+ ID to equal the signed `vibe_show_page_id`.
+- Replacing an email audience bumps the paired Instance authorization revision
+ when and only when the normalized set changes, invalidating existing sessions
+ after the normal revision refresh.
+
+## Management Contract
+
+- The local Avibe service exposes owner-authorized ShowPage email GET/PUT APIs.
+- Those handlers call a paired-device-authenticated control-plane endpoint; the
+ device secret never reaches the browser.
+- Personal and Organization instances use the same email-grant endpoint.
+- Organization audience/group management continues through the existing
+ Organization management flow and remains orthogonal to email grants.
+
+## Verification
+
+- Backend store, route, authorization, authorize-request, frozen-code, and ID
+ token tests.
+- App OIDC claim, cookie, exact-route, exact-resource, API, and UI tests.
+- Regression coverage proving one email grant cannot open another ShowPage or
+ any Workbench/API surface.
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index 89de80db5..8d9f217b3 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -243,6 +243,7 @@ def metadata_with_resource_user_context(
"vibe_membership_version": context.membership_version,
"vibe_instance_role": context.instance_role,
"vibe_instance_access_source": context.instance_access_source,
+ "vibe_show_page_id": context.show_page_id,
"claims_issued_at": context.claims_issued_at,
"vibe_instance_authorization_revision": context.authorization_revision,
"authorization_expires_at": _resource_context_expires_at(context),
@@ -542,11 +543,14 @@ def _replace_policy_groups(
def _policy_allows(
context: ResourceUserContext,
resource_kind: str,
+ resource_id: str,
policy: Mapping[str, Any] | None,
group_ids: Sequence[str],
) -> bool:
if context.is_trusted_local:
return True
+ if context.instance_access_source == "show_page_email":
+ return resource_kind == "show_page" and context.can_use_show_page(resource_id)
if not context.can_use_resource(resource_kind):
return False
if policy is None:
@@ -660,6 +664,7 @@ def can_use_resource_policy_snapshot(
return _policy_allows(
context,
str(resource_kind),
+ str(policy.get("resource_id") or ""),
policy,
[str(group_id) for group_id in group_ids],
)
@@ -689,7 +694,7 @@ def can_use_resource(
with _connection(connection) as conn:
policy = _policy_row(conn, kind, identifier)
groups = _policy_groups(conn, kind, identifier) if policy else []
- return _policy_allows(context, kind, policy, groups)
+ return _policy_allows(context, kind, identifier, policy, groups)
def can_manage_resource_acl(
@@ -791,7 +796,13 @@ def filter_accessible_resources(
row
for row, identifier in candidates
if identifier is not None
- and _policy_allows(context, kind, policies.get(identifier), groups.get(identifier, []))
+ and _policy_allows(
+ context,
+ kind,
+ identifier,
+ policies.get(identifier),
+ groups.get(identifier, []),
+ )
]
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index d840f6f1a..07cc3345a 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -184,7 +184,7 @@ scenarios:
backend: cloud_management
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_silent_reauthorization_stops_after_login_required
- id: AUTH-SETUP-307
- name: Remote Organization callback remains bound to the same subject
+ name: Remote Organization callback remains subject-bound and returns failures to its workflow
status: covered
kind: authorization
layer: scenario
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 2e2f0d55e..18f030e03 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -197,13 +197,14 @@ class OrganizationManagementAuthScenarioTests(unittest.TestCase):
def test_remote_callback_keeps_the_bound_subject(self):
"""Scenario: AUTH-SETUP-307"""
backend = SimpleNamespace(base_url="https://avibe.bot")
+ next_path = "/chat/session-1?tab=show-page"
with patch.object(cloud_management, "_validated_backend", return_value=backend):
_, state = cloud_management.begin_authorization(
self.harness.config,
browser_id="browser-1",
remote_subject="user-1",
callback_origin=REMOTE_ORIGIN,
- next_path="/admin/organization/overview",
+ next_path=next_path,
silent=False,
)
client = self.harness.remote_client(subject="user-2")
@@ -229,7 +230,10 @@ class OrganizationManagementAuthScenarioTests(unittest.TestCase):
base_url=REMOTE_ORIGIN,
)
self.assertEqual(response.status_code, 302)
- self.assertIn("cloud_management_error=cloud_management_subject_mismatch", response.headers["location"])
+ self.assertEqual(
+ response.headers["location"],
+ f"{next_path}&cloud_management_error=cloud_management_subject_mismatch",
+ )
self.assertNotIn("not-exposed", response.text)
def test_trusted_loopback_flow_can_establish_the_first_subject(self):
diff --git a/tests/test_cloud_management.py b/tests/test_cloud_management.py
index c2ed424c3..7bde047f5 100644
--- a/tests/test_cloud_management.py
+++ b/tests/test_cloud_management.py
@@ -104,6 +104,26 @@ def test_management_return_path_allows_only_supported_same_origin_workflows(
assert cloud_management.validate_next_path(candidate) == expected
+def test_management_return_path_is_visible_only_to_the_bound_browser(monkeypatch, tmp_path) -> None:
+ config = _save_config(monkeypatch, tmp_path)
+ backend = SimpleNamespace(base_url="https://avibe.bot")
+ monkeypatch.setattr(cloud_management, "_validated_backend", lambda _config: backend)
+ _, state = cloud_management.begin_authorization(
+ config,
+ browser_id="browser-1",
+ remote_subject="user-1",
+ callback_origin=REMOTE_ORIGIN,
+ next_path="/chat/session-1?tab=show-page",
+ silent=False,
+ )
+
+ assert cloud_management.handshake_next_path(state, "browser-1") == (
+ "/chat/session-1?tab=show-page"
+ )
+ assert cloud_management.handshake_next_path(state, "browser-2") is None
+ assert cloud_management.handshake_next_path("missing-state", "browser-1") is None
+
+
def test_local_start_uses_https_handoff_and_never_exposes_token(monkeypatch, tmp_path) -> None:
_save_config(monkeypatch, tmp_path)
captured: dict[str, object] = {}
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index c73d287ef..d1319fc9f 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -95,6 +95,40 @@ def test_malformed_role_context_fails_closed() -> None:
assert context.can_read_instance is False
+def test_show_page_email_context_requires_and_matches_one_exact_target() -> None:
+ context = context_from_session_payload(
+ {
+ "sub": "guest-1",
+ "email": "[email protected]",
+ "vibe_instance_id": "inst-1",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": "session-one",
+ "vibe_instance_authorization_revision": 0,
+ }
+ )
+
+ assert context.can_use_show_page("session-one") is True
+ assert context.can_use_show_page("session-two") is False
+ assert context.show_page_id == "session-one"
+
+ missing_target = context_from_session_payload(
+ {
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ }
+ )
+ unexpected_target = context_from_session_payload(
+ {
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "email",
+ "vibe_show_page_id": "session-one",
+ }
+ )
+ assert missing_target.can_read_instance is False
+ assert unexpected_target.can_read_instance is False
+
+
def test_http_policy_defaults_unknown_api_to_owner() -> None:
assert required_instance_role("GET", "/api/projects") == "viewer"
assert required_instance_role("GET", "/api/projects/proj-1") == "viewer"
diff --git a/tests/test_remote_authorization_revision.py b/tests/test_remote_authorization_revision.py
index a976538a0..9c803e6b9 100644
--- a/tests/test_remote_authorization_revision.py
+++ b/tests/test_remote_authorization_revision.py
@@ -156,14 +156,14 @@ def test_revision_advance_revokes_active_editor_http_session(
tmp_path,
hosted_change,
):
- """I1057-AC1/AC2: narrowing invalidates a remote session with chat disabled."""
+ """I1057-AC1/AC2: narrowing invalidates a remote session with chat enabled."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
cookie = _organization_cookie(config)
payload = remote_access.parse_session_cookie(config, cookie)
assert payload is not None
- assert context_from_session_payload(payload).can_chat is False
+ assert context_from_session_payload(payload).can_chat is True
client = app.test_client()
client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.py
index d8d8e5797..534112cd8 100644
--- a/tests/test_resource_acl_show_pages.py
+++ b/tests/test_resource_acl_show_pages.py
@@ -114,6 +114,43 @@ def test_show_page_list_filters_private_public_scope_and_missing_group_context(m
assert no_group_ids == {"ses-public"}
+def test_show_page_email_context_bypasses_audience_only_for_its_signed_page(
+ monkeypatch, tmp_path
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = _seed_show_pages_with_policies()
+ context = resource_access_service.ResourceUserContext(
+ subject="guest-1",
+ instance_role="viewer",
+ instance_access_source="show_page_email",
+ show_page_id="ses-private",
+ is_remote=True,
+ )
+ try:
+ with store.engine.connect() as connection:
+ assert resource_access_service.can_use_resource(
+ context,
+ "show_page",
+ "ses-private",
+ connection=connection,
+ )
+ assert not resource_access_service.can_use_resource(
+ context,
+ "show_page",
+ "ses-public",
+ connection=connection,
+ )
+ assert not resource_access_service.can_use_resource(
+ context,
+ "agent",
+ "ses-private",
+ connection=connection,
+ )
+ finally:
+ store.close()
+
+
def test_remote_show_page_list_and_direct_requests_enforce_policy(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
@@ -285,6 +322,32 @@ def test_access_only_manager_visibility_response_does_not_expose_page_payload(mo
assert result == {"ok": True, "public_link_enabled": False}
+def test_excluded_scoped_owner_share_mutations_do_not_expose_page_payload(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ store = _seed_show_pages_with_policies()
+ excluded_owner = _organization_context(
+ "owner-1",
+ group_ids=frozenset({"group-sales"}),
+ instance_role="viewer",
+ )
+ try:
+ store.update_visibility("ses-scope", "public", user_context=excluded_owner)
+ finally:
+ store.close()
+ monkeypatch.setattr(
+ resource_access_service,
+ "resolve_resource_access_context",
+ lambda _value=None: excluded_owner,
+ )
+
+ rotated = api.rotate_show_page_share("ses-scope")
+ customized = api.set_show_page_share_id("ses-scope", "excluded-owner-link")
+
+ assert rotated == {"ok": True, "public_link_enabled": True}
+ assert customized == {"ok": True, "public_link_enabled": True}
+
+
def test_remote_show_page_owner_can_control_sharing_without_instance_owner_role(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
@@ -498,6 +561,144 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monk
}
+def test_show_page_owner_can_read_and_replace_exact_email_grants(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ store.ensure("ses-email-access")
+ finally:
+ store.close()
+
+ calls: list[tuple] = []
+ monkeypatch.setattr(
+ remote_access,
+ "get_show_page_authorized_emails",
+ lambda show_page_id: calls.append(("GET", show_page_id))
+ or {"emails": ["[email protected]"]},
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "replace_show_page_authorized_emails",
+ lambda show_page_id, emails: calls.append(("PUT", show_page_id, emails))
+ or {"emails": emails, "changed": True},
+ )
+ client = app.test_client()
+
+ loaded = client.get("/api/show-pages/ses-email-access/authorized-emails")
+ replaced = client.put(
+ "/api/show-pages/ses-email-access/authorized-emails",
+ json={"emails": [" [email protected] ", "[email protected]"]},
+ headers=csrf_headers(client),
+ )
+
+ assert loaded.status_code == 200
+ assert loaded.get_json() == {"ok": True, "emails": ["[email protected]"]}
+ assert loaded.headers["Cache-Control"] == "no-store, private"
+ assert replaced.status_code == 200
+ assert replaced.get_json() == {
+ "ok": True,
+ "emails": ["[email protected]"],
+ "changed": True,
+ }
+ assert calls == [
+ ("GET", "ses-email-access"),
+ ("PUT", "ses-email-access", ["[email protected]"]),
+ ]
+
+
+def test_show_page_email_grants_reject_non_manager_without_contacting_backend(
+ monkeypatch, tmp_path
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = _seed_show_pages_with_policies()
+ store.close()
+ monkeypatch.setattr(
+ resource_access_service,
+ "resolve_resource_access_context",
+ lambda _value=None: _organization_context("member-1"),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "get_show_page_authorized_emails",
+ lambda _show_page_id: pytest.fail("backend must not be contacted"),
+ )
+
+ response = app.test_client().get(
+ "/api/show-pages/ses-public/authorized-emails"
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "resource_access_forbidden"
+
+
+def test_show_page_email_grants_report_unavailable_without_cloud_pairing(
+ monkeypatch, tmp_path
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ store = ShowPageStore()
+ try:
+ store.ensure("ses-email-access")
+ finally:
+ store.close()
+
+ response = app.test_client().get(
+ "/api/show-pages/ses-email-access/authorized-emails"
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()["code"] == "show_page_email_access_not_configured"
+
+
+def test_show_page_email_grant_device_requests_freeze_the_target(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ calls: list[tuple] = []
+ monkeypatch.setattr(remote_access, "_resource_acl_sync_configured", lambda _config: True)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda cfg, method, suffix, payload=None: calls.append(
+ (cfg, method, suffix, payload)
+ )
+ or (
+ {"emails": ["[email protected]"]}
+ if method == "GET"
+ else {
+ "emails": ["[email protected]"],
+ "changed": True,
+ "authorization_revision": 9,
+ }
+ ),
+ )
+ revisions: list[int] = []
+ monkeypatch.setattr(
+ remote_access,
+ "_replace_authorization_revision",
+ lambda _config, revision: revisions.append(revision) or revision,
+ )
+
+ loaded = remote_access.get_show_page_authorized_emails("session/one", config)
+ replaced = remote_access.replace_show_page_authorized_emails(
+ "session/one",
+ config,
+ )
+
+ assert loaded == {"emails": ["[email protected]"]}
+ assert replaced == {"emails": ["[email protected]"], "changed": True}
+ assert calls == [
+ (config, "GET", "show-pages/session%2Fone/authorized-emails", None),
+ (
+ config,
+ "PUT",
+ "show-pages/session%2Fone/authorized-emails",
+ {"emails": ["[email protected]"]},
+ ),
+ ]
+ assert revisions == [9]
+
+
def test_remote_dock_filters_private_pins_and_authorizes_mutations(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index e45682327..b0ed67fdc 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -139,6 +139,102 @@ def test_remote_host_redirects_to_vibe_cloud_login(monkeypatch, tmp_path):
assert state_payload["retry"] is False
+def test_private_show_page_login_freezes_target_in_authorize_and_handshake(
+ monkeypatch, tmp_path
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+
+ response = app.test_client().get(
+ "/show/session-one/asset.js",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 302
+ authorize_params = httpx.URL(response.headers["Location"]).params
+ assert authorize_params["show_page_id"] == "session-one"
+ state_payload = ui_server._read_oauth_state(
+ config.remote_access.vibe_cloud.session_secret,
+ authorize_params["state"],
+ )
+ assert state_payload is not None
+ stored = remote_access._oauth_handshakes[state_payload["r"]]
+ assert stored["show_page_id"] == "session-one"
+
+
+def test_show_page_email_session_is_confined_to_its_signed_route(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ cookie = remote_access.make_session_cookie(
+ config,
+ "guest-1",
+ session_claims={
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": "session-one",
+ },
+ )
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ cookie,
+ domain="alex.avibe.bot",
+ )
+
+ exact = client.get(
+ "/show/session-one/missing.js",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ other = client.get(
+ "/show/session-two/",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ workbench = client.get(
+ "/api/show-pages",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ session_api = client.get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert exact.status_code != 403
+ assert other.status_code == 403
+ assert other.get_json()["error"] == "show_page_access_forbidden"
+ assert workbench.status_code == 403
+ assert session_api.status_code == 403
+
+
+def test_show_page_oidc_claim_shape_fails_closed(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ base = {
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ }
+
+ with pytest.raises(remote_access.OAuthCodeExchangeError, match="invalid_show_page_id"):
+ remote_access.session_claims_from_oidc(config, base)
+ with pytest.raises(remote_access.OAuthCodeExchangeError, match="invalid_show_page_id"):
+ remote_access.session_claims_from_oidc(
+ config,
+ {
+ **base,
+ "vibe_instance_access_source": "email",
+ "vibe_show_page_id": "session-one",
+ },
+ )
+
+
def test_custom_hostname_uses_remote_auth_until_heartbeat_removes_it(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
@@ -2909,6 +3005,61 @@ def test_remote_callback_rejects_nonce_mismatch(monkeypatch, tmp_path):
assert 'href="/dashboard"' in response.text
+def test_remote_callback_rejects_show_page_email_token_for_a_different_page(
+ monkeypatch, tmp_path
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+
+ with app.test_request_context(
+ "/show/session-one/",
+ base_url="https://alex.avibe.bot",
+ ):
+ redirect = ui_server._redirect_to_vibe_cloud_login(config)
+ oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]
+ client.set_cookie(
+ ui_server.REMOTE_OAUTH_COOKIE_NAME,
+ oauth_cookie,
+ domain="alex.avibe.bot",
+ )
+ oauth_state = ui_server._read_oauth_cookie(
+ config.remote_access.vibe_cloud.session_secret,
+ oauth_cookie,
+ )
+
+ monkeypatch.setattr(
+ remote_access,
+ "exchange_oauth_code",
+ lambda cfg, code, verifier, redirect_uri=None: {
+ "claims": {
+ "email": "[email protected]",
+ "sub": "guest-1",
+ "nonce": oauth_state["nonce"],
+ },
+ "session_claims": {
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": "session-two",
+ },
+ },
+ )
+
+ response = client.get(
+ f"/auth/callback?code=test-code&state={oauth_state['state']}",
+ base_url="https://alex.avibe.bot",
+ )
+
+ assert response.status_code == 400
+ assert "invalid_show_page_id" in response.text
+ assert 'href="/show/session-one/"' in response.text
+ assert not any(
+ header.startswith(f"{remote_access.SESSION_COOKIE_NAME}=")
+ for header in response.headers.getlist("Set-Cookie")
+ )
+
+
def test_remote_callback_externalizes_large_organization_claims(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
diff --git a/ui/src/components/workbench/ShowPageEmailAccessEditor.tsx b/ui/src/components/workbench/ShowPageEmailAccessEditor.tsx
new file mode 100644
index 000000000..b661f837a
--- /dev/null
+++ b/ui/src/components/workbench/ShowPageEmailAccessEditor.tsx
@@ -0,0 +1,235 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import clsx from 'clsx';
+import { CloudOff, Loader2, Mail, Plus, RefreshCw, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { ApiError, useApi } from '@/context/ApiContext';
+import { normalizeShowPageAuthorizedEmail } from '@/lib/showPageAccess';
+
+type EmailAccessGate = 'idle' | 'loading' | 'ready' | 'unavailable' | 'error';
+
+const normalizedSet = (emails: string[]): string[] => [...new Set(emails)].sort();
+
+const emailAccessUnavailable = (error: unknown): boolean => error instanceof ApiError
+ && [
+ 'show_page_email_access_not_configured',
+ 'show_page_email_access_unavailable',
+ ].includes(error.code ?? '');
+
+export function ShowPageEmailAccessEditor({
+ active,
+ canManage,
+ sessionId,
+}: {
+ active: boolean;
+ canManage: boolean;
+ sessionId: string;
+}) {
+ const { t } = useTranslation();
+ const api = useApi();
+ const [gate, setGate] = useState<EmailAccessGate>('idle');
+ const [emails, setEmails] = useState<string[]>([]);
+ const [savedEmails, setSavedEmails] = useState<string[]>([]);
+ const [draft, setDraft] = useState('');
+ const [draftInvalid, setDraftInvalid] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const generationRef = useRef(0);
+
+ const load = useCallback(async () => {
+ const generation = ++generationRef.current;
+ setGate('loading');
+ try {
+ const result = await api.getShowPageAuthorizedEmails(sessionId);
+ if (generation !== generationRef.current) return;
+ const next = normalizedSet(result.emails);
+ setEmails(next);
+ setSavedEmails(next);
+ setGate('ready');
+ } catch (error) {
+ if (generation !== generationRef.current) return;
+ setGate(emailAccessUnavailable(error) ? 'unavailable' : 'error');
+ }
+ }, [api, sessionId]);
+
+ useEffect(() => {
+ generationRef.current += 1;
+ setGate('idle');
+ setEmails([]);
+ setSavedEmails([]);
+ setDraft('');
+ setDraftInvalid(false);
+ setSaving(false);
+ if (active && canManage) void load();
+ return () => {
+ generationRef.current += 1;
+ };
+ }, [active, canManage, load, sessionId]);
+
+ const dirty = useMemo(
+ () => emails.join('\u0000') !== savedEmails.join('\u0000'),
+ [emails, savedEmails],
+ );
+
+ if (!canManage) return null;
+
+ const addDraft = () => {
+ const normalized = normalizeShowPageAuthorizedEmail(draft);
+ if (!normalized) {
+ setDraftInvalid(true);
+ return;
+ }
+ setEmails((current) => normalizedSet([...current, normalized]));
+ setDraft('');
+ setDraftInvalid(false);
+ };
+
+ const save = async () => {
+ if (!dirty || saving || draft.trim()) return;
+ setSaving(true);
+ try {
+ const result = await api.replaceShowPageAuthorizedEmails(sessionId, emails);
+ const next = normalizedSet(result.emails);
+ setEmails(next);
+ setSavedEmails(next);
+ setGate('ready');
+ } catch (error) {
+ setGate(emailAccessUnavailable(error) ? 'unavailable' : 'error');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <div className="space-y-2.5 border-t border-border pt-2.5">
+ <div className="flex items-start gap-2">
+ <Mail className="mt-0.5 size-3.5 shrink-0 text-muted" />
+ <div className="min-w-0">
+ <div className="text-xs font-medium">{t('chat.showPage.emailAccess')}</div>
+ <p className="mt-0.5 text-[11px] leading-snug text-muted">
+ {t('chat.showPage.emailAccessDesc')}
+ </p>
+ </div>
+ </div>
+
+ {gate === 'loading' || gate === 'idle' ? (
+ <div className="flex items-center gap-1.5 text-[11px] text-muted">
+ <Loader2 className="size-3.5 animate-spin" />
+ {t('chat.showPage.loadingEmailAccess')}
+ </div>
+ ) : null}
+
+ {gate === 'unavailable' ? (
+ <div className="flex items-start gap-1.5 text-[11px] leading-snug text-muted">
+ <CloudOff className="mt-0.5 size-3.5 shrink-0" />
+ {t('chat.showPage.emailAccessUnavailable')}
+ </div>
+ ) : null}
+
+ {gate === 'error' ? (
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] leading-snug text-destructive">
+ {t('chat.showPage.emailAccessError')}
+ </span>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0"
+ onClick={() => void load()}
+ aria-label={t('common.retry')}
+ title={t('common.retry')}
+ >
+ <RefreshCw className="size-3.5" />
+ </Button>
+ </div>
+ ) : null}
+
+ {gate === 'ready' ? (
+ <>
+ <div className="flex items-start gap-1.5">
+ <div className="min-w-0 flex-1">
+ <Input
+ type="email"
+ value={draft}
+ disabled={saving || emails.length >= 64}
+ onChange={(event) => {
+ setDraft(event.target.value);
+ if (draftInvalid) setDraftInvalid(false);
+ }}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter') return;
+ event.preventDefault();
+ addDraft();
+ }}
+ placeholder={t('chat.showPage.emailPlaceholder')}
+ aria-label={t('chat.showPage.emailAccess')}
+ aria-invalid={draftInvalid || undefined}
+ className={clsx('h-8 text-xs', draftInvalid && 'border-destructive')}
+ />
+ {draftInvalid ? (
+ <p className="mt-1 text-[11px] text-destructive">
+ {t('chat.showPage.emailInvalid')}
+ </p>
+ ) : null}
+ </div>
+ <Button
+ type="button"
+ size="icon"
+ variant="outline"
+ className="size-8 shrink-0"
+ disabled={saving || !draft.trim() || emails.length >= 64}
+ onClick={addDraft}
+ aria-label={t('chat.showPage.addEmail')}
+ title={t('chat.showPage.addEmail')}
+ >
+ <Plus className="size-3.5" />
+ </Button>
+ </div>
+
+ {emails.length ? (
+ <div className="max-h-32 divide-y divide-border overflow-y-auto rounded-md border border-border">
+ {emails.map((email) => (
+ <div key={email} className="flex min-h-8 items-center gap-2 px-2">
+ <span className="min-w-0 flex-1 truncate font-mono text-[11px]">{email}</span>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-6 shrink-0"
+ disabled={saving}
+ onClick={() => setEmails((current) => current.filter((value) => value !== email))}
+ aria-label={t('chat.showPage.removeEmail', { email })}
+ title={t('chat.showPage.removeEmail', { email })}
+ >
+ <X className="size-3" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="text-[11px] leading-snug text-muted">
+ {t('chat.showPage.emailAccessEmpty')}
+ </p>
+ )}
+
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-[10px] text-muted">{t('chat.showPage.emailAccessLimit')}</span>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7"
+ disabled={!dirty || saving || Boolean(draft.trim())}
+ onClick={() => void save()}
+ >
+ {saving ? <Loader2 className="size-3.5 animate-spin" /> : null}
+ {t('chat.showPage.applyEmailAccess')}
+ </Button>
+ </div>
+ </>
+ ) : null}
+ </div>
+ );
+}
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
index b6ffbf04e..594f269d9 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
@@ -11,6 +11,16 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
+vi.mock('@/context/ApiContext', () => ({
+ ApiError: class ApiError extends Error {
+ code = null;
+ },
+ useApi: () => ({
+ getShowPageAuthorizedEmails: vi.fn(),
+ replaceShowPageAuthorizedEmails: vi.fn(),
+ }),
+}));
+
vi.mock('@/components/ui/confirm-dialog', () => ({
ConfirmDialog: ({ open, title }: { open: boolean; title: string }) => (
<div data-confirm-open={String(open)}>{title}</div>
@@ -58,7 +68,7 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(html).toContain('<button');
});
- it('renders Personal as a fixed Private audience without Organization choices', () => {
+ it('gives Personal an email audience without Organization choices', () => {
const html = renderControl(access({
mode: 'personal',
instance_id: null,
@@ -71,6 +81,7 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(html).not.toContain('chat.showPage.workspaceLevels.public');
expect(html).not.toContain('chat.showPage.workspaceLevels.scope');
expect(html).not.toContain('<select');
+ expect(html).toContain('chat.showPage.emailAccess');
});
it('renders all Organization audiences and keeps the public wire value labeled as Organization', () => {
@@ -80,6 +91,7 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(html).toContain('value="public" selected=""');
expect(html).toContain('value="scope"');
expect(html).toContain('chat.showPage.workspaceLevels.public');
+ expect(html).toContain('chat.showPage.emailAccess');
});
it('keeps the Organization audience read-only for a non-owner viewer', () => {
@@ -87,6 +99,7 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(html).toContain('<select disabled=""');
expect(html).toContain('chat.showPage.workspaceReadOnly');
+ expect(html).not.toContain('chat.showPage.emailAccessDesc');
});
it('mounts the established Organization audience-narrowing confirmation', () => {
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
index b2551b1f6..a9b2e584c 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
@@ -39,6 +39,7 @@ import {
showPageSyncPresentation,
type ShowPageAccess,
} from '@/lib/showPageAccess';
+import { ShowPageEmailAccessEditor } from './ShowPageEmailAccessEditor';
type ManagementGate =
| 'idle'
@@ -430,6 +431,14 @@ export function ShowPageWorkspaceAccessControl({
</Button>
</div>
) : null}
+
+ {access ? (
+ <ShowPageEmailAccessEditor
+ active={active}
+ canManage={canManage}
+ sessionId={sessionId}
+ />
+ ) : null}
</section>
<ConfirmDialog
open={confirmNarrowing}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index ccdfb79d3..fca69a740 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -13,6 +13,7 @@ import {
classifyShowPageAccessProbe,
type ShowPageAccess,
type ShowPageAccessProbe,
+ type ShowPageAuthorizedEmails,
type ShowPageVisibilityResult,
} from '../lib/showPageAccess';
import {
@@ -498,6 +499,11 @@ export type ApiContextType = {
getShowPages: () => Promise<any>;
getShowPageAccess: (sessionId: string) => Promise<ShowPageAccess>;
probeShowPageAccess: (sessionId: string) => Promise<ShowPageAccessProbe>;
+ getShowPageAuthorizedEmails: (sessionId: string) => Promise<ShowPageAuthorizedEmails>;
+ replaceShowPageAuthorizedEmails: (
+ sessionId: string,
+ emails: string[],
+ ) => Promise<ShowPageAuthorizedEmails>;
getWebPushStatus: (payload?: WebPushStatusPayload) => Promise<WebPushStatus>;
getWebPushVapidPublicKey: () => Promise<{ ok: boolean; public_key: string }>;
subscribeWebPush: (
@@ -2228,6 +2234,36 @@ export class ApiError extends Error {
}
}
+async function requestShowPageAuthorizedEmails(
+ sessionId: string,
+ init?: RequestInit,
+): Promise<ShowPageAuthorizedEmails> {
+ const path = `/api/show-pages/${encodeURIComponent(sessionId)}/authorized-emails`;
+ const response = await apiFetch(path, init);
+ const payload: unknown = await response.json().catch(() => ({}));
+ if (!response.ok) {
+ const fallback = `Request failed: ${path} (${response.status})`;
+ const parsed = selectApiErrorFields(payload, fallback);
+ throw new ApiError(
+ parsed?.fallback ?? fallback,
+ response.status,
+ parsed?.code ?? null,
+ );
+ }
+ if (
+ !payload
+ || typeof payload !== 'object'
+ || (payload as Partial<ShowPageAuthorizedEmails>).ok !== true
+ || !Array.isArray((payload as Partial<ShowPageAuthorizedEmails>).emails)
+ || (payload as Partial<ShowPageAuthorizedEmails>).emails?.some(
+ (email) => typeof email !== 'string',
+ )
+ ) {
+ throw new ApiError('Invalid Show Page email access response.', 502, null);
+ }
+ return payload as ShowPageAuthorizedEmails;
+}
+
const ApiContext = createContext<ApiContextType | undefined>(undefined);
const CONFIG_CACHE_TTL_MS = 30_000;
@@ -2831,6 +2867,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return { status: 'error', access: null };
}
},
+ getShowPageAuthorizedEmails: (sessionId) => requestShowPageAuthorizedEmails(sessionId),
+ replaceShowPageAuthorizedEmails: (sessionId, emails) => requestShowPageAuthorizedEmails(
+ sessionId,
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ emails }),
+ },
+ ),
getWebPushStatus: (payload) =>
payload ? postJson('/api/web-push/status', payload) : getJson('/api/web-push/status'),
getWebPushVapidPublicKey: () => getJson('/api/web-push/vapid-public-key'),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c15e01e5a..9f8cabef5 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3201,6 +3201,18 @@
"offline": "This Avibe is offline. The audience change will apply after it reconnects.",
"error": "This Avibe could not apply the audience change."
},
+ "emailAccess": "Specific emails",
+ "emailAccessDesc": "These signed-in email addresses can open only this Show Page.",
+ "emailPlaceholder": "[email protected]",
+ "addEmail": "Add email",
+ "removeEmail": "Remove {{email}}",
+ "emailInvalid": "Enter a valid email address.",
+ "emailAccessEmpty": "No additional email addresses have access.",
+ "emailAccessLimit": "Up to 64 email addresses",
+ "applyEmailAccess": "Apply",
+ "loadingEmailAccess": "Loading email access…",
+ "emailAccessUnavailable": "Email access requires an Avibe Cloud connection.",
+ "emailAccessError": "Email access could not be loaded.",
"accessLoadError": "Access details could not be loaded. Sharing changes are disabled.",
"publicLink": "Public link",
"publicLinkOnDesc": "Anyone with the link can open this page without signing in.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b22c3f80f..47373b711 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3201,6 +3201,18 @@
"offline": "当前 Avibe 已离线,重新连接后会应用访问范围变更。",
"error": "当前 Avibe 无法应用访问范围变更。"
},
+ "emailAccess": "指定邮箱",
+ "emailAccessDesc": "这些邮箱登录后只能打开当前 Show Page。",
+ "emailPlaceholder": "[email protected]",
+ "addEmail": "添加邮箱",
+ "removeEmail": "移除 {{email}}",
+ "emailInvalid": "请输入有效的邮箱地址。",
+ "emailAccessEmpty": "尚未授权额外邮箱。",
+ "emailAccessLimit": "最多 64 个邮箱",
+ "applyEmailAccess": "应用",
+ "loadingEmailAccess": "正在加载邮箱权限…",
+ "emailAccessUnavailable": "连接 Avibe Cloud 后才能设置邮箱权限。",
+ "emailAccessError": "无法加载邮箱权限。",
"accessLoadError": "无法加载权限详情,分享设置已停用。",
"publicLink": "公开链接",
"publicLinkOnDesc": "任何人都可以通过链接直接打开,无需登录。",
diff --git a/ui/src/lib/showPageAccess.test.ts b/ui/src/lib/showPageAccess.test.ts
index 2fa096bd0..07120182a 100644
--- a/ui/src/lib/showPageAccess.test.ts
+++ b/ui/src/lib/showPageAccess.test.ts
@@ -6,6 +6,7 @@ import {
canChangeShowPagePublicLink,
classifyShowPageAccessProbe,
isShowPageVisibilityPayload,
+ normalizeShowPageAuthorizedEmail,
showPageShareCapabilities,
showPageHeaderAccess,
showPageAudienceLabelKey,
@@ -44,6 +45,14 @@ describe('Show Page access policy helpers', () => {
expect(showPageAudienceLabelKey('public')).toBe('chat.showPage.workspaceLevels.public');
});
+ it('normalizes exact email grants with the backend validation contract', () => {
+ expect(normalizeShowPageAuthorizedEmail(' [email protected] ')).toBe(
+ );
+ expect(normalizeShowPageAuthorizedEmail('guest@example')).toBeNull();
+ expect(normalizeShowPageAuthorizedEmail('guest@')).toBeNull();
+ });
+
it('requires at least one group for scoped access and normalizes duplicates', () => {
expect(buildShowPageAccessPatch('scope', [], 4)).toBeNull();
expect(buildShowPageAccessPatch('scope', ['group-1', ' group-1 ', 'group-2'], 4)).toEqual({
diff --git a/ui/src/lib/showPageAccess.ts b/ui/src/lib/showPageAccess.ts
index d1e75a9aa..f9e262749 100644
--- a/ui/src/lib/showPageAccess.ts
+++ b/ui/src/lib/showPageAccess.ts
@@ -33,6 +33,19 @@ export type ShowPageVisibilityResult<Payload extends ShowPageLinkInfo = ShowPage
| ShowPageVisibilityPayload<Payload>
| ShowPageVisibilityMetadata;
+export type ShowPageAuthorizedEmails = {
+ ok: true;
+ emails: string[];
+ changed?: boolean;
+};
+
+const SHOW_PAGE_EMAIL_PATTERN = /^[a-z0-9._%+-]+@[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}$/;
+
+export function normalizeShowPageAuthorizedEmail(raw: string): string | null {
+ const normalized = raw.trim().toLowerCase();
+ return SHOW_PAGE_EMAIL_PATTERN.test(normalized) ? normalized : null;
+}
+
function isShowPageAccess(value: unknown): value is ShowPageAccess {
if (!value || typeof value !== 'object') return false;
const candidate = value as Partial<ShowPageAccess>;
diff --git a/vibe/api.py b/vibe/api.py
index cfc60bffe..7eb956a3e 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1340,38 +1340,56 @@ def list_show_pages() -> dict:
}
+def _show_page_mutation_response(
+ store,
+ page,
+ *,
+ config: V2Config,
+ additional_payload: dict | None = None,
+) -> dict:
+ """Return mutation details only when the caller can use the page."""
+ from storage import resource_access_service
+
+ context = resource_access_service.resolve_resource_access_context()
+ with store.engine.connect() as connection:
+ can_use = resource_access_service.can_use_resource(
+ context,
+ "show_page",
+ page.session_id,
+ connection=connection,
+ )
+ if not can_use:
+ # Audience managers may revoke an anonymous link without page-use
+ # access. Do not return page paths, URLs, share IDs, or session metadata.
+ return {
+ "ok": True,
+ "public_link_enabled": page.visibility == "public",
+ }
+ from core.show_pages import show_page_payload
+
+ payload = show_page_payload(page, config=config)
+ return {
+ "ok": True,
+ **(additional_payload or {}),
+ **_apply_session_meta([payload])[0],
+ }
+
+
def set_show_page_visibility(session_id: str, visibility: str) -> dict:
"""Switch a Show Page between private / public / offline.
Raises ``ShowPageError`` (a ``ValueError``) for invalid input, which the
route layer maps to a 4xx response.
"""
- from core.show_pages import ShowPageStore, show_page_payload
- from storage import resource_access_service
+ from core.show_pages import ShowPageStore
config = V2Config.load()
- context = resource_access_service.resolve_resource_access_context()
store = ShowPageStore()
try:
updated = store.update_visibility(session_id, visibility)
- with store.engine.connect() as connection:
- can_use = resource_access_service.can_use_resource(
- context,
- "show_page",
- session_id,
- connection=connection,
- )
- payload = show_page_payload(updated, config=config) if can_use else None
+ return _show_page_mutation_response(store, updated, config=config)
finally:
store.close()
- if payload is None:
- # Audience managers may revoke an anonymous link without page-use
- # access. Do not return page paths, URLs, share IDs, or session metadata.
- return {
- "ok": True,
- "public_link_enabled": updated.visibility == "public",
- }
- return {"ok": True, **_apply_session_meta([payload])[0]}
def ensure_show_page(session_id: str) -> dict:
@@ -1459,18 +1477,97 @@ def get_show_page_access(session_id: str) -> dict:
}
+def _require_show_page_email_access_management(session_id: str) -> None:
+ from core.show_pages import ShowPageError, ShowPageStore
+ from storage import resource_access_service
+
+ context = resource_access_service.resolve_resource_access_context()
+ store = ShowPageStore()
+ try:
+ page = store.get(session_id)
+ if page is None:
+ raise ShowPageError("This session has no Show Page.", code="show_page_not_found")
+ with store.engine.connect() as connection:
+ if not resource_access_service.can_manage_show_page_access(
+ context,
+ page.session_id,
+ connection=connection,
+ ):
+ raise ShowPageError(
+ "Show Page access is not permitted.",
+ code="resource_access_forbidden",
+ )
+ finally:
+ store.close()
+
+
+def _show_page_email_access_error(exc: Exception):
+ from core.show_pages import ShowPageError
+ from vibe import remote_access
+
+ if isinstance(exc, ShowPageError):
+ return exc
+ if isinstance(exc, remote_access.BackendRequestError):
+ code = str(exc.payload.get("error") or "show_page_email_access_unavailable")
+ else:
+ code = str(exc) or "show_page_email_access_unavailable"
+ if code not in {
+ "invalid_email",
+ "too_many_entries",
+ "show_page_email_access_not_configured",
+ "show_page_email_access_invalid_response",
+ }:
+ code = "show_page_email_access_unavailable"
+ return ShowPageError(code, code=code)
+
+
+def get_show_page_authorized_emails(session_id: str) -> dict:
+ """Return exact email grants for one owner-managed Show Page."""
+
+ from vibe import remote_access
+
+ _require_show_page_email_access_management(session_id)
+ try:
+ result = remote_access.get_show_page_authorized_emails(session_id)
+ except Exception as exc:
+ raise _show_page_email_access_error(exc) from exc
+ return {"ok": True, "emails": result["emails"]}
+
+
+def replace_show_page_authorized_emails(session_id: str, emails: list[str]) -> dict:
+ """Replace one Show Page's exact email grants through paired-device auth."""
+
+ from vibe import remote_access
+
+ _require_show_page_email_access_management(session_id)
+ normalized = sorted({str(email).strip().lower() for email in emails if str(email).strip()})
+ try:
+ result = remote_access.replace_show_page_authorized_emails(session_id, normalized)
+ except Exception as exc:
+ raise _show_page_email_access_error(exc) from exc
+ return {
+ "ok": True,
+ "emails": result["emails"],
+ "changed": result["changed"],
+ }
+
+
def rotate_show_page_share(session_id: str) -> dict:
"""Revoke the current public link and issue a new one (public pages only)."""
- from core.show_pages import ShowPageStore, show_page_payload
+ from core.show_pages import ShowPageStore
config = V2Config.load()
store = ShowPageStore()
try:
updated, previous_share_id = store.rotate_share(session_id)
- payload = show_page_payload(updated, config=config)
+ return _show_page_mutation_response(
+ store,
+ updated,
+ config=config,
+ additional_payload={"previous_share_id": previous_share_id},
+ )
finally:
store.close()
- return {"ok": True, "previous_share_id": previous_share_id, **_apply_session_meta([payload])[0]}
def set_show_page_share_id(session_id: str, share_id: str) -> dict:
@@ -1480,16 +1577,20 @@ def set_show_page_share_id(session_id: str, share_id: str) -> dict:
revokes the previous public URL. Raises ``ShowPageError`` for an invalid /
taken suffix or a non-public page, which the route layer maps to a 4xx/409.
"""
- from core.show_pages import ShowPageStore, show_page_payload
+ from core.show_pages import ShowPageStore
config = V2Config.load()
store = ShowPageStore()
try:
updated, previous_share_id = store.set_share_id(session_id, share_id)
- payload = show_page_payload(updated, config=config)
+ return _show_page_mutation_response(
+ store,
+ updated,
+ config=config,
+ additional_payload={"previous_share_id": previous_share_id},
+ )
finally:
store.close()
- return {"ok": True, "previous_share_id": previous_share_id, **_apply_session_meta([payload])[0]}
def upload_show_page_icon(
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 81c10d4e7..1f7118137 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -9,7 +9,14 @@ from typing import Any, Mapping
INSTANCE_ROLES = frozenset({"owner", "editor", "viewer"})
INSTANCE_ACCESS_SOURCES = frozenset(
- {"owner", "public_instance", "email", "email_domain", "organization_group"}
+ {
+ "owner",
+ "public_instance",
+ "email",
+ "email_domain",
+ "organization_group",
+ "show_page_email",
+ }
)
ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
_ROLE_RANK = {"viewer": 1, "editor": 2, "owner": 3}
@@ -61,6 +68,7 @@ class AuthorizationContext:
membership_version: str | None = None
claims_issued_at: int | None = None
authorization_revision: int | None = None
+ show_page_id: str | None = None
is_remote: bool = False
is_trusted_local: bool = False
@@ -118,6 +126,15 @@ class AuthorizationContext:
minimum_role = _RESOURCE_USE_MINIMUM_ROLES.get(resource_kind)
return minimum_role is not None and self.has_role(minimum_role)
+ def can_use_show_page(self, show_page_id: str) -> bool:
+ """Return whether a Show Page-only session targets this exact page."""
+
+ return bool(
+ self.instance_access_source == "show_page_email"
+ and self.show_page_id
+ and self.show_page_id == show_page_id
+ )
+
@property
def can_use_terminal_files(self) -> bool:
return not self.is_remote and self.has_role("owner")
@@ -193,6 +210,9 @@ def context_from_session_payload(payload: Mapping[str, Any]) -> AuthorizationCon
)
if access_source not in INSTANCE_ACCESS_SOURCES:
return AuthorizationContext(is_remote=True)
+ show_page_id = _optional_string(payload.get("vibe_show_page_id"), limit=200)
+ if (access_source == "show_page_email") != (show_page_id is not None):
+ return AuthorizationContext(is_remote=True)
raw_groups = payload.get("vibe_group_ids", payload.get("group_ids", []))
group_ids = (
frozenset(value for item in raw_groups if (value := _optional_string(item)) is not None)
@@ -230,6 +250,7 @@ def context_from_session_payload(payload: Mapping[str, Any]) -> AuthorizationCon
payload.get("authorization_revision"),
)
),
+ show_page_id=show_page_id,
is_remote=True,
)
@@ -312,6 +333,7 @@ _VIEWER_HTTP_RULES = tuple(
r"^/api/resource-policies$",
r"^/api/show-pages$",
r"^/api/show-pages/[^/]+/access$",
+ r"^/api/show-pages/[^/]+/authorized-emails$",
r"^/api/show-pages/[^/]+/icon$",
)
)
@@ -323,6 +345,7 @@ _VIEWER_HTTP_MUTATION_RULES = tuple(
("POST", r"^/api/show-pages/[^/]+/visibility$"),
("POST", r"^/api/show-pages/[^/]+/rotate-share$"),
("POST", r"^/api/show-pages/[^/]+/share-id$"),
+ ("PUT", r"^/api/show-pages/[^/]+/authorized-emails$"),
)
)
@@ -402,6 +425,10 @@ _REMOTE_OWNER_ALLOWED_HTTP_RULES = tuple(
frozenset({"POST"}),
r"^/api/show-pages/[^/]+/(?:ensure|rotate-share|share-id|visibility)$",
),
+ (
+ frozenset({"GET", "HEAD", "PUT"}),
+ r"^/api/show-pages/[^/]+/authorized-emails$",
+ ),
(frozenset({"GET", "HEAD"}), r"^/api/dock$"),
(frozenset({"POST"}), r"^/api/dock/pins$"),
(frozenset({"DELETE"}), r"^/api/dock/pins/[^/]+$"),
diff --git a/vibe/cloud_management.py b/vibe/cloud_management.py
index 9df1fd4ac..018f3b4b2 100644
--- a/vibe/cloud_management.py
+++ b/vibe/cloud_management.py
@@ -259,6 +259,16 @@ def authorization_url_for_handoff(
return _authorization_url(config, _validated_backend(config).base_url, handshake), handshake.browser_id
+def handshake_next_path(state: str | None, browser_id: str | None) -> str | None:
+ """Return a handshake's safe next path only to its bound browser."""
+ if not state or not browser_id:
+ return None
+ handshake = handshake_for_handoff(state)
+ if handshake is None or not secrets.compare_digest(handshake.browser_id, browser_id):
+ return None
+ return validate_next_path(handshake.next_path)
+
+
def pop_handshake(state: str) -> ManagementHandshake | None:
with _lock:
_prune_locked(time.time())
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 7b143c1c8..a5e3a62e1 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -55,7 +55,7 @@ _SESSION_AUTHORIZATION_REFERENCE_RE = re.compile(r"\A[A-Za-z0-9_-]{24,64}\Z")
OAUTH_ID_TOKEN_CLOCK_LEEWAY_SECONDS = 30
_INSTANCE_ACCESS_ROLES = frozenset({"owner", "editor", "viewer"})
_INSTANCE_ACCESS_SOURCES = frozenset(
- {"owner", "public_instance", "email", "email_domain", "organization_group"}
+ {"owner", "public_instance", "email", "email_domain", "organization_group", "show_page_email"}
)
_ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
_CONNECTOR_LOCK = threading.RLock()
@@ -114,7 +114,9 @@ _RESOURCE_ACL_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error
_RESOURCE_ACL_MAX_REVISION = (1 << 53) - 1
_RESOURCE_ACL_PENDING_VAULT_RELEASE_PREFIX = "resource_acl_pending_vault_release:"
_INSTANCE_ACCESS_ROLES = frozenset({"owner", "editor", "viewer"})
-_INSTANCE_ACCESS_SOURCES = frozenset({"owner", "public_instance", "email", "email_domain", "organization_group"})
+_INSTANCE_ACCESS_SOURCES = frozenset(
+ {"owner", "public_instance", "email", "email_domain", "organization_group", "show_page_email"}
+)
_ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
_BLOCKED_PAIRING_BACKEND_HOSTS = {
"localhost",
@@ -1491,6 +1493,60 @@ def _device_json_request(
return parsed
+def _show_page_email_grant_suffix(show_page_id: str) -> str:
+ encoded = urllib.parse.quote(show_page_id, safe="")
+ return f"show-pages/{encoded}/authorized-emails"
+
+
+def get_show_page_authorized_emails(
+ show_page_id: str,
+ config: V2Config | None = None,
+) -> dict[str, Any]:
+ """Load one Show Page's exact email grants through paired-device auth."""
+
+ config = config or V2Config.load()
+ if not _resource_acl_sync_configured(config):
+ raise RuntimeError("show_page_email_access_not_configured")
+ result = _device_json_request(
+ config,
+ "GET",
+ _show_page_email_grant_suffix(show_page_id),
+ )
+ emails = result.get("emails")
+ if not isinstance(emails, list) or any(not isinstance(email, str) for email in emails):
+ raise RuntimeError("show_page_email_access_invalid_response")
+ return {"emails": emails}
+
+
+def replace_show_page_authorized_emails(
+ show_page_id: str,
+ emails: list[str],
+ config: V2Config | None = None,
+) -> dict[str, Any]:
+ """Replace one Show Page's email grants without exposing the device secret."""
+
+ config = config or V2Config.load()
+ if not _resource_acl_sync_configured(config):
+ raise RuntimeError("show_page_email_access_not_configured")
+ result = _device_json_request(
+ config,
+ "PUT",
+ _show_page_email_grant_suffix(show_page_id),
+ {"emails": emails},
+ )
+ returned_emails = result.get("emails")
+ if not isinstance(returned_emails, list) or any(
+ not isinstance(email, str) for email in returned_emails
+ ):
+ raise RuntimeError("show_page_email_access_invalid_response")
+ if result.get("authorization_revision") is not None:
+ _replace_authorization_revision(config, result["authorization_revision"])
+ return {
+ "emails": returned_emails,
+ "changed": bool(result.get("changed")),
+ }
+
+
def sync_authorization_revision_once(
config: V2Config | None = None,
) -> dict[str, Any]:
@@ -4136,6 +4192,18 @@ def session_claims_from_oidc(config: V2Config, claims: Mapping[str, Any]) -> dic
"vibe_instance_role": instance_role,
"vibe_instance_access_source": access_source,
}
+ show_page_claim_present = "vibe_show_page_id" in claims
+ if access_source == "show_page_email":
+ show_page_id = _oidc_claim_string(
+ claims.get("vibe_show_page_id"),
+ reason="invalid_show_page_id",
+ limit=200,
+ )
+ if "/" in show_page_id or "\\" in show_page_id:
+ raise OAuthCodeExchangeError("invalid_show_page_id")
+ session_claims["vibe_show_page_id"] = show_page_id
+ elif show_page_claim_present:
+ raise OAuthCodeExchangeError("invalid_show_page_id")
raw_authorization_revision = claims.get(_AUTHORIZATION_REVISION_KEY)
if raw_authorization_revision is None:
if _authorization_revision_sync_configured(config):
@@ -4360,6 +4428,7 @@ def authorization_url(
nonce: str,
code_challenge: str,
redirect_uri: str | None = None,
+ show_page_id: str | None = None,
) -> str:
cloud = config.remote_access.vibe_cloud
params = {
@@ -4374,6 +4443,8 @@ def authorization_url(
}
if cloud.dev_login_hint:
params["login_hint"] = cloud.dev_login_hint
+ if show_page_id:
+ params["show_page_id"] = show_page_id
return f"{cloud.authorization_endpoint}?{urllib.parse.urlencode(params)}"
@@ -4498,6 +4569,7 @@ def store_oauth_handshake(
next_target: str,
device_hash: str | None = None,
redirect_uri: str | None = None,
+ show_page_id: str | None = None,
) -> None:
"""Persist a login handshake in memory, keyed by the signed state's random id.
@@ -4513,6 +4585,7 @@ def store_oauth_handshake(
"next": next_target,
"device_hash": device_hash,
"redirect_uri": redirect_uri,
+ "show_page_id": show_page_id,
"exp": now + OAUTH_HANDSHAKE_TTL_SECONDS,
}
with _OAUTH_STORE_LOCK:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 026968956..f61ca4d11 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1650,6 +1650,18 @@ def _oauth_callback_arg(name: str) -> str | None:
return request.args.get(name) or request.args.get(f"amp;{name}")
+def _show_page_id_from_private_route(path: str) -> str | None:
+ match = re.match(r"^/show/([^/]+)(?:/|$)", path or "")
+ if match is None:
+ return None
+ try:
+ from core.show_pages import validate_session_id
+
+ return validate_session_id(unquote(match.group(1)))
+ except Exception:
+ return None
+
+
def _redirect_to_vibe_cloud_login(config: V2Config):
from vibe import remote_access
@@ -1659,6 +1671,7 @@ def _redirect_to_vibe_cloud_login(config: V2Config):
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
raw_next = request.full_path if request.query_string else request.path
next_target = _strip_oauth_retry_param(raw_next)
+ show_page_id = _show_page_id_from_private_route(request.path)
rid = secrets.token_urlsafe(18)
state = _make_oauth_state(
cloud.session_secret,
@@ -1684,6 +1697,7 @@ def _redirect_to_vibe_cloud_login(config: V2Config):
next_target=next_target,
device_hash=_oauth_device_hash(cloud.session_secret, device_id),
redirect_uri=redirect_uri,
+ show_page_id=show_page_id,
)
oauth_cookie = _make_oauth_cookie(
cloud.session_secret,
@@ -1693,6 +1707,7 @@ def _redirect_to_vibe_cloud_login(config: V2Config):
"code_verifier": code_verifier,
"next": next_target,
"redirect_uri": redirect_uri,
+ "show_page_id": show_page_id,
"exp": int(datetime.now().timestamp()) + REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS,
},
)
@@ -1703,6 +1718,7 @@ def _redirect_to_vibe_cloud_login(config: V2Config):
nonce,
code_challenge,
redirect_uri=redirect_uri,
+ show_page_id=show_page_id,
)
response.set_cookie(
REMOTE_OAUTH_COOKIE_NAME,
@@ -2206,6 +2222,52 @@ def enforce_remote_access_cookie():
return jsonify({"ok": False, "error": "remote_access_login_required"}), 401
+def enforce_show_page_email_scope():
+ """Keep an email-grant session inside its one signed Show Page subtree."""
+
+ config = _load_remote_access_config()
+ if config is None or not _is_remote_access_request(config):
+ return None
+ context = getattr(g, "authorization_context", None)
+ if context is None:
+ from vibe import remote_access
+ from vibe.authorization import context_from_session_payload
+
+ payload = remote_access.parse_session_cookie(
+ config,
+ request.cookies.get(remote_access.SESSION_COOKIE_NAME),
+ )
+ if payload is not None:
+ context = context_from_session_payload(payload)
+ if context is None or context.instance_access_source != "show_page_email":
+ return None
+
+ path = request.path or ""
+ public_static = (
+ path.startswith("/assets/")
+ or path.startswith(f"{_SHOW_RUNTIME_VENDOR_PREFIX}/")
+ or path.startswith("/p/")
+ or path == "/favicon.ico"
+ or path in _PWA_PUBLIC_ASSETS
+ or path
+ in {
+ _SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH,
+ _SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH,
+ "/auth/callback",
+ "/auth/logout",
+ "/health",
+ }
+ )
+ expected_prefix = f"/show/{context.show_page_id}" if context.show_page_id else ""
+ exact_show_page = bool(
+ expected_prefix and (path == expected_prefix or path.startswith(f"{expected_prefix}/"))
+ )
+ if public_static or exact_show_page:
+ return None
+ return jsonify({"ok": False, "error": "show_page_access_forbidden"}), 403
+
+
@app.before_request
def enforce_instance_role_capabilities():
if _remote_auth_exempt_path():
@@ -2434,6 +2496,8 @@ def enforce_project_role_capabilities():
return None
kind, resource_id = resource
+ if kind == "session" and context.can_use_show_page(resource_id):
+ return None
engine = create_sqlite_engine()
with engine.connect() as conn:
role = (
@@ -3066,6 +3130,8 @@ def _project_session_access_allowed(context: Any, session_id: str, minimum_role:
return True
if not context.has_role(minimum_role):
return False
+ if minimum_role == "viewer" and context.can_use_show_page(session_id):
+ return True
engine = _projects_engine()
with engine.connect() as conn:
role = project_access_service.get_effective_session_role(
@@ -4739,6 +4805,41 @@ def show_page_access_get(session_id):
return _show_page_error_response(exc)
[email protected]("/api/show-pages/<session_id>/authorized-emails", methods=["GET"])
+def show_page_authorized_emails_get(session_id):
+ from core.show_pages import ShowPageError
+ from vibe import api
+
+ try:
+ response = jsonify(api.get_show_page_authorized_emails(session_id))
+ response.headers["Cache-Control"] = "no-store, private"
+ response.headers["Vary"] = "Cookie"
+ return response
+ except ShowPageError as exc:
+ return _show_page_error_response(exc)
+
+
[email protected]("/api/show-pages/<session_id>/authorized-emails", methods=["PUT"])
+def show_page_authorized_emails_put(session_id):
+ from core.show_pages import ShowPageError
+ from vibe import api
+
+ payload = request.json if isinstance(request.json, dict) else {}
+ emails = payload.get("emails")
+ if (
+ not isinstance(emails, list)
+ or len(emails) > 64
+ or any(not isinstance(email, str) for email in emails)
+ ):
+ return _show_page_error_response(
+ ShowPageError("Invalid Show Page email audience.", code="invalid_email")
+ )
+ try:
+ return jsonify(api.replace_show_page_authorized_emails(session_id, emails))
+ except ShowPageError as exc:
+ return _show_page_error_response(exc)
+
+
@app.route("/api/show-pages/<session_id>/rotate-share", methods=["POST"])
def show_page_rotate_share_post(session_id):
from core.show_pages import ShowPageError
@@ -5754,6 +5855,10 @@ def cloud_management_auth_callback():
_mark_cloud_management_manual(response)
return response
browser_id = request.cookies.get(cloud_management.BROWSER_COOKIE_NAME) or ""
+ failure_next_path = (
+ cloud_management.handshake_next_path(state, browser_id)
+ or "/admin/organization/overview"
+ )
try:
grant, next_path = cloud_management.complete_authorization(
config,
@@ -5769,7 +5874,7 @@ def cloud_management_auth_callback():
else "cloud_management_unavailable"
)
response = _cloud_management_redirect(
- "/admin/organization/overview",
+ failure_next_path,
code,
)
cloud_management.invalidate_grant(
@@ -6017,6 +6122,7 @@ def remote_access_auth_callback():
handshake_nonce = cookie_state.get("nonce")
next_target = cookie_state.get("next")
redirect_uri = str(cookie_state.get("redirect_uri") or cloud.redirect_uri)
+ expected_show_page_id = cookie_state.get("show_page_id")
elif store_record is not None and _oauth_store_record_device_bound(cloud.session_secret, store_record):
# Store-fallback for the iOS standalone PWA case, where the handshake cookie's
# state desyncs (authorize ran in a separate in-app-browser context). Gated on
@@ -6029,6 +6135,7 @@ def remote_access_auth_callback():
handshake_nonce = store_record.get("nonce")
next_target = store_record.get("next")
redirect_uri = str(store_record.get("redirect_uri") or cloud.redirect_uri)
+ expected_show_page_id = store_record.get("show_page_id")
else:
# Neither the cookie nor the server-side store yielded the handshake.
# Rate-limited: this branch is unauthenticated-reachable.
@@ -6058,6 +6165,11 @@ def remote_access_auth_callback():
session_claims = result.get("session_claims")
if not isinstance(session_claims, dict):
raise remote_access.OAuthCodeExchangeError("invalid_session_claims")
+ if session_claims.get("vibe_instance_access_source") == "show_page_email" and (
+ not isinstance(expected_show_page_id, str)
+ or session_claims.get("vibe_show_page_id") != expected_show_page_id
+ ):
+ raise remote_access.OAuthCodeExchangeError("invalid_show_page_id")
except Exception as exc:
# Unauthenticated-reachable (valid handshake + bad code), so rate-limited.
reason = exc.reason if isinstance(exc, remote_access.OAuthCodeExchangeError) else exc.__class__.__name__