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.

fix(auth): make remote authorization seamless (#1468)

Max065eb85869f9
diff --git a/docs/plans/issue-1433-1434-session-and-push-authorization.md b/docs/plans/issue-1433-1434-session-and-push-authorization.md
new file mode 100644
index 000000000..5c6893315
--- /dev/null
+++ b/docs/plans/issue-1433-1434-session-and-push-authorization.md
@@ -0,0 +1,390 @@
+# Issues 1433 and 1434: seamless session and Push authorization
+
+Status: #1433 implementation complete; #1434 requires a separate follow-up.
+
+Implementation snapshot (2026-08-15):
+
+- Backend prerequisite `avibe-backend` PR #229 is merged, with `main` and `dev`
+ synchronized at `a3f8e4b`; its Production deployment must be verified before
+ the App rollout.
+- App #1433 foundation, migration, shared resolver, non-blocking scheduled
+ Organization refresh, transport enforcement, frontend recovery, logout
+ isolation, and `AUTH-SETUP-402` / `AUTH-SETUP-403` coverage are implemented
+ on `fix-issue-1433-seamless-authorization`.
+- The branch was rebased onto `master` commit `5822a49e`, including upstream
+ PR #1441 as unchanged base behavior. Current evidence is 836 related Python
+ tests and all 2,759 frontend tests passing, plus Ruff and the production UI
+ build.
+- Upstream `master` independently merged PR #1441 for #1434 while this work was
+ in progress. Rebase and compatibility review must keep that existing Push
+ delivery change out of the #1433 diff, then identify any remaining #1434
+ gaps in a separate follow-up.
+- Incus and real iOS PWA checks remain integration evidence after backend #229
+ is deployed; this branch must not merge before that deployment is verified.
+
+Review circuit-breaker decision (2026-08-15):
+
+- Codex findings-bearing heads were `ad8c339743` (6 findings), `298691f973`
+ (2 findings), and `8b8f24b2f5` (3 findings). The third head triggered a
+ whole-model review before further edits.
+- The remaining transport finding class came from treating current authority as
+ the complete live-session gate. A live SSE or WebSocket must first revalidate
+ the accepted entry proof against the latest config: remote access is enabled,
+ the original host is still configured, and the original cookie still parses
+ to the same identity under the current session secret. Only then may it call
+ the shared current-authorization resolver. One helper owns this check for all
+ private SSE and WebSocket loops.
+- The unavailable cold-load finding belongs to the existing frontend recovery
+ state machine, not a new retry mechanism. AuthGuard reports the initial state
+ to `remoteAuth`, which owns the bounded probe and manual retry timer.
+- Application WebSocket close codes are observable only after the handshake is
+ accepted. Initial Terminal and Show Runtime authorization failures therefore
+ accept and immediately close without starting either protected service; other
+ origin and generic policy rejections retain their existing handshake behavior.
+- This review decision does not expand #1434 Push delivery, persistence, or
+ backend contracts.
+
+Review follow-up decision (2026-08-15):
+
+- A new cookie's opaque authorization reference is deliberately not a signed
+ scope hint. If that referenced row is missing, the resolver must not guess an
+ Instance scope and call the backchannel: it fails closed as
+ `invalid_identity` with `authorization_record_missing`, so normal login can
+ create a fresh correctly scoped row. Legacy inline-claims cookies without a
+ reference keep their compatibility migration path. A storage read failure is
+ `unavailable`, not a fake logout.
+- Private Show event replay revalidates current authorization once before each
+ persisted batch, not before every event. A batch is bounded at 500 events;
+ subsequent batches and the live loop retain their existing checks, preserving
+ revocation while keeping replay work proportional to batch count.
+- These corrections stay inside #1433's identity/current-authorization and
+ long-lived transport boundaries. They do not add cookie fields, persistence
+ types, retry machinery, or any of #1434's remaining Push behavior.
+
+- [#1433](https://github.com/avibe-bot/avibe/issues/1433): restore the Personal
+ session experience and separate Personal/Organization authorization policy.
+- [#1434](https://github.com/avibe-bot/avibe/issues/1434): stop normal Web Push
+ from depending on prompt-time claims snapshots.
+
+## Root cause and scope
+
+Both bugs come from treating one short-lived browser claims snapshot as four
+different things: browser identity, current authorization, live-connection
+lifetime, and Push authority. Fix the boundary once, then make HTTP, SSE,
+WebSocket, and Push consume the same current-authorization result.
+
+Keep the architecture small:
+
+- one paired-device authorization query in `avibe-backend`;
+- one shared resolver in the App;
+- one evolved `remote_access_authorizations` store;
+- no refresh-token lifecycle, routine browser `prompt=none`, second auth store,
+ or durable Push queue.
+
+Confirmed decisions:
+
+- Organization control-plane outage grace is 6 hours.
+- After 6 hours, identity stays authenticated while protected operations return
+ `authorization_unavailable`; an outage never redirects to OAuth.
+- Push may send a fully redacted fallback when authorization is unknown.
+ Confirmed revocation or Project denial sends nothing.
+
+## User experience contract
+
+1. Sign in once, then use Avibe without routine authorization prompts.
+2. Personal activity slides a 24-hour local session beyond both 12 and 24 hours.
+3. Organization refresh and revision recovery happen through the device
+ backchannel without opening a browser sheet or losing the requested route.
+4. Only invalid/expired browser identity starts interactive login.
+5. Confirmed access removal stops protected HTTP, SSE, WebSocket, and Push.
+6. Temporary backend failure is an unavailable state, never a fake logout.
+7. Explicit logout closes that browser's live connections and disables that
+ device's Push subscription without signing out the user's other devices.
+
+Expiry of the hosted avibe.bot browser session does not end an otherwise valid
+local session. It matters only when interactive identity recovery is actually
+needed.
+
+## Policy contract
+
+Define independently owned values rather than global constants plus call-site
+exceptions.
+
+| Behavior | Personal | Organization |
+| --- | --- | --- |
+| Identity TTL | 24 hours | 24 hours initially, independently named |
+| Renewal | Slide after half-life on an accepted request | Independent setting; no browser OAuth just because renewal is due |
+| Routine auth refresh | None in browser | 12-hour device backchannel initially |
+| Revision | Background invalidation hint, never a request gate | Prompt poll; mismatch triggers one backchannel refresh |
+| Revision outage | Keep last-known authority | Keep last-known authority for 6 hours |
+| After grace | Continue under Personal policy | Authenticated but protected operations unavailable |
+| Confirmed removal | Revoke | Revoke |
+
+Personal request authorization must not evaluate Organization membership/group
+logic, revision freshness, or revision snapshot age. A successfully observed
+global revision change may schedule a background refresh, but failure of that
+hint never blocks Personal access.
+
+Unknown `instance_kind` must not default to Personal. First backfill from runtime
+status or the new auth response; until then, retain the existing strict policy.
+The poller must reload config/policy inside its loop so backfill takes effect
+without restart.
+
+## Backend prerequisite
+
+Add this low-privilege paired-runtime endpoint in `avibe-backend`, following the
+existing `user-token` device-secret boundary:
+
+```http
+POST /api/v1/instances/:instanceId/authorization-context
+X-Vibe-Device-Secret: <paired device secret>
+
+{
+ "sub": "hosted-user-id",
+ "email": "[email protected]",
+ "show_page_id": "optional-show-page-id"
+}
+```
+
+The endpoint:
+
+- authenticates the Instance/device secret;
+- calls `authorizeInteractiveInstanceAccess()`;
+- returns only current Instance claims, `authorization_revision`, and
+ `instance_kind`, or `access_denied`;
+- preserves `show_page_email` as Show Page-only authority;
+- shares one claim-projection helper with OIDC issuance so role, source,
+ Organization, group, Show Page, and revision fields cannot drift;
+- updates device last-seen consistently with the existing broker route;
+- does not mint Cloud tokens or expose Organization directory data.
+
+The App may send identity only from a signed cookie or trusted App-owned auth
+record. Message `author_id`, arbitrary request bodies, and untrusted metadata
+are never identity sources.
+
+Contract tests cover Personal, Organization/group, public interactive access,
+Show Page-only access, denial, invalid identity, and invalid device secret.
+
+## App foundation for #1433
+
+### Identity and current authorization
+
+Split `parse_session_cookie()` into:
+
+- identity parsing: size, signature, Instance binding, subject, identity expiry;
+- authorization resolution: local record, selected policy, optional backchannel
+ refresh;
+- transport mapping: HTTP/SSE/WebSocket response behavior.
+
+Use one result contract:
+
+```text
+resolve_current_authorization(identity, optional_scope)
+ -> current(context, refreshed=false|true)
+ -> revoked
+ -> unavailable
+```
+
+Invalid/expired identity is separate from these outcomes. Concurrent callers for
+the same `instance + subject + scope` share one bounded, process-local refresh so
+API, SSE, WebSocket, and Push cannot create an auth storm.
+
+Keep a synchronous core for middleware/Push and an async wrapper for SSE/WS that
+runs blocking device I/O through the existing threadpool. Do not block the ASGI
+loop or add `asyncio.run()` to request paths.
+
+### Persistence and migration
+
+Evolve `remote_access_authorizations`; do not add a competing claims table.
+Add nullable columns:
+
+```text
+email
+scope_kind # instance | show_page for new rows
+scope_ref # instance id | show page id for new rows
+authorization_state # current | revoked for authoritative results
+last_checked_at # last successful hosted check
+updated_at
+```
+
+Keep the authorization revision in `claims_json`; do not duplicate every claim
+into columns. New records upsert through a partial unique index on:
+
+```text
+instance_id + subject + scope_kind + scope_ref
+```
+
+Instance and Show Page scopes never overwrite each other. Legacy random-ref rows
+keep `scope_kind IS NULL` and their current `expires_at` behavior. New scoped
+records are durable for Push, so `expires_at` becomes nullable for them. New
+login/renewal silently writes the scoped shape; old cookies/rows load until
+normal expiry.
+
+`unavailable` is computed and never overwrites last-known claims as if they were
+revoked. The 6-hour window starts at the last successful authoritative contact,
+not local traffic. A revision poll extends a record only if its revision still
+matches; mismatch must refresh or revoke it.
+
+Malformed optional rows disable only that feature/row with a warning. Startup
+and trusted local access must continue. Unpairing or changing Instance identity
+invalidates records for the old Instance.
+
+### Cookie renewal
+
+Use a renewal path distinct from initial OIDC cookie creation:
+
+- renew to a fresh 24-hour expiry after half-life on an accepted request;
+- preserve `claims_issued_at` on a pure cookie slide;
+- update it only after authoritative authorization refresh;
+- preserve a browser-session id across renewal so logout can close that
+ browser's connections;
+- seed missing session ids on legacy-cookie renewal;
+- update the local revision snapshot directly from successful OIDC claims
+ instead of making a second hosted request.
+
+The resolver uses the durable record's current claims/check time, so a Push-side
+refresh does not become stale merely because a browser cookie was not reissued.
+
+### Transport and frontend integration
+
+Replace direct cookie/revision checks in middleware, `/api/session`,
+`/api/cloud/token`, Workbench SSE, Show Page SSE, Show Runtime HMR, Terminal WS,
+and any remaining direct consumer.
+
+HTTP mapping:
+
+- invalid/expired identity: `401 remote_access_login_required`;
+- confirmed revocation: `403 remote_access_revoked`;
+- unavailable after grace: `503 remote_access_authorization_unavailable`;
+- current/cached within policy: continue.
+
+`/api/session` returns `authenticated: true` plus `authorization_state` while
+unavailable. Static assets, health, session diagnostics, and logout remain
+reachable, but protected data does not.
+
+Long-lived connections independently enforce identity expiry, confirmed
+revocation, Organization grace expiry, Project/Show Page ACL change, and logout.
+Before closing, emit distinct outcomes: WS `4401` login required, `4403` revoked,
+and `4503` temporarily unavailable, with equivalent SSE terminal events.
+
+Extend the existing `ui/src/lib/remoteAuth.ts` as the one frontend recovery
+owner for API, SSE, and WS:
+
+- login required preserves route and the existing iOS PWA user-gesture rule;
+- revoked shows terminal access denied without OAuth retry;
+- unavailable keeps the shell stable and retries with bounded backoff;
+- current clears the recoverable state.
+
+Remove Terminal's independent `4401 -> window.location.reload()`. Logout
+publishes browser-session invalidation before deleting the cookie and accepts
+the current Push device id/endpoint so only that subscription is disabled.
+
+## Normal Push for #1434
+
+New authenticated user-message metadata stores trusted `user_key` values only,
+not `_web_push_authorization_contexts` snapshots. At delivery:
+
+1. Resolve trusted owner user keys using existing authenticated-ingress rules.
+2. Resolve current authorization through the shared resolver.
+3. Re-check current local Project ACL with that context.
+4. Select only that owner's enabled subscriptions.
+5. Send full, redacted, or nothing according to the disposition.
+
+Legacy full-context metadata remains compatibility input. It may bootstrap
+subject/email/scope, but aged claims are not accepted as current Organization
+authority. Never trust `author_id` or queued/untrusted metadata as owner.
+
+Dispositions:
+
+```text
+sent
+sent_redacted
+revoked
+project_denied
+authorization_unavailable
+no_owner
+no_subscription
+provider_failure
+```
+
+- Current and Project-visible: full payload.
+- Revision changed: refresh once, then decide.
+- Unavailable: one short retry, then redacted fallback.
+- Revoked/Project denied: no delivery.
+- Provider `404/410`: retain subscription-disable behavior.
+- No durable retry queue.
+
+Fixed redacted payload:
+
+```text
+Title: Avibe
+Body: New activity is available
+Action: Open Avibe
+URL: /inbox
+```
+
+The outbound payload must contain no message text, Project/session name, badge,
+message/session id, resource tag, or resource deep link.
+
+Keep `/api/web-push/test` transport-only. Add nullable subscription diagnostics:
+
+```text
+last_normal_disposition
+last_normal_attempt_at
+last_normal_message_id
+```
+
+Expose the selected subscription's current auth state and last normal
+disposition through `/api/web-push/status`, without claims, content, other users'
+endpoints, or credentials.
+
+## Compatibility and rollout
+
+- Old cookies, random auth rows, and messages with full Push contexts remain
+ readable and silently migrate on safe success.
+- New messages remain schema-readable without full claims.
+- Endpoint `404`, timeout, or malformed response means unavailable, never revoked
+ or startup failure.
+- Deploy the backend endpoint before App changes. In a mixed-version window,
+ Personal keeps last-known policy; Organization uses 6-hour grace, then
+ unavailable rather than OAuth.
+
+Use three PRs:
+
+1. `avibe-backend`: endpoint, shared projection, contract tests. Small-medium,
+ about 1-2 engineering days.
+2. `avibe-app` for #1433: policies, migration, resolver, cookie, transports,
+ logout, frontend recovery, auth scenario coverage. Large, about 4-6 days.
+3. `avibe-app` for #1434: metadata change, Push resolver/ACL, fallback,
+ dispositions/status, regression tests. Medium, about 2-3 days.
+
+Allow 1-2 additional days for cross-repo review, deployment, Incus regression,
+and real iOS PWA checks. The total is large because #1433 crosses all transports,
+not because it introduces a large framework.
+
+## Verification
+
+Automated coverage must prove:
+
+- Personal sliding use beyond 12/24 hours and preserved `claims_issued_at`;
+- Personal policy isolation from Organization groups/revision liveness;
+- Organization silent scheduled/mismatch refresh, 6-hour grace, recovery, and
+ authenticated-but-unavailable after grace;
+- confirmed removal and logout across HTTP, SSE, WS, and Push;
+- unknown-kind backfill changes live policy without restart;
+- Instance versus Show Page scope isolation and current Project ACL narrowing;
+- `/api/cloud/token` uses the shared result without coupling to hosted browser
+ session liveness;
+- Personal normal Push after the old 12-hour cutoff;
+- unavailable Push sends only the fixed redacted payload after one retry;
+- revoked/Project-denied Push sends nothing;
+- provider `404/410`, legacy metadata/rows, and normal-path diagnostics.
+
+Update `tests/scenarios/auth_setup/catalog.yaml` and its closed-loop scenario
+harness for the browser flows. Use test-owned config/SQLite/network stubs only.
+Run focused tests and Ruff, plus the UI build for frontend changes.
+
+After review passes, update the local Incus `master` environment through the
+runner and verify HTTP, SSE, Terminal/Show Runtime WS, logout, Personal sliding,
+Organization outage/revocation, and normal/test Push diagnostics. Record real
+iOS PWA notification behavior as the remaining manual evidence.
diff --git a/storage/alembic/versions/20260815_0054_remote_authorization_context.py b/storage/alembic/versions/20260815_0054_remote_authorization_context.py
new file mode 100644
index 000000000..ed59ba035
--- /dev/null
+++ b/storage/alembic/versions/20260815_0054_remote_authorization_context.py
@@ -0,0 +1,116 @@
+"""persist current remote authorization contexts
+
+Revision ID: 20260815_0054
+Revises: 20260812_0053
+Create Date: 2026-08-15
+"""
+
+from __future__ import annotations
+
+from alembic import op
+import sqlalchemy as sa
+
+revision = "20260815_0054"
+down_revision = "20260812_0053"
+branch_labels = None
+depends_on = None
+
+
+def _columns() -> set[str]:
+ return {
+ str(row[1])
+ for row in op.get_bind()
+ .exec_driver_sql('pragma table_info("remote_access_authorizations")')
+ .fetchall()
+ }
+
+
+def _indexes() -> set[str]:
+ return {
+ str(row[1])
+ for row in op.get_bind()
+ .exec_driver_sql('pragma index_list("remote_access_authorizations")')
+ .fetchall()
+ }
+
+
+def upgrade() -> None:
+ columns = _columns()
+ additions = (
+ ("email", sa.String()),
+ ("scope_kind", sa.String()),
+ ("scope_ref", sa.String()),
+ ("authorization_state", sa.String()),
+ ("last_checked_at", sa.Integer()),
+ ("updated_at", sa.Integer()),
+ )
+ for name, column_type in additions:
+ if name not in columns:
+ op.add_column(
+ "remote_access_authorizations",
+ sa.Column(name, column_type, nullable=True),
+ )
+
+ # Scoped records are durable and therefore do not have a row expiry. SQLite
+ # requires a table rebuild to relax the legacy NOT NULL constraint.
+ expires = next(
+ (
+ row
+ for row in op.get_bind()
+ .exec_driver_sql('pragma table_info("remote_access_authorizations")')
+ .fetchall()
+ if str(row[1]) == "expires_at"
+ ),
+ None,
+ )
+ if expires is not None and int(expires[3]) == 1:
+ with op.batch_alter_table("remote_access_authorizations") as batch_op:
+ batch_op.alter_column(
+ "expires_at",
+ existing_type=sa.Integer(),
+ nullable=True,
+ )
+
+ if "ux_remote_access_authorizations_scope" not in _indexes():
+ op.create_index(
+ "ux_remote_access_authorizations_scope",
+ "remote_access_authorizations",
+ ["instance_id", "subject", "scope_kind", "scope_ref"],
+ unique=True,
+ sqlite_where=sa.text("scope_kind is not null and scope_ref is not null"),
+ )
+
+
+def downgrade() -> None:
+ if "ux_remote_access_authorizations_scope" in _indexes():
+ op.drop_index(
+ "ux_remote_access_authorizations_scope",
+ table_name="remote_access_authorizations",
+ )
+ # Pre-0054 readers require an expiry and cannot represent scoped durable
+ # contexts. Remove only the new shape before restoring the legacy NOT NULL
+ # contract; legacy random-reference rows remain untouched.
+ op.execute(
+ sa.text(
+ "delete from remote_access_authorizations "
+ "where scope_kind is not null or scope_ref is not null"
+ )
+ )
+ columns = _columns()
+ removable = (
+ "updated_at",
+ "last_checked_at",
+ "authorization_state",
+ "scope_ref",
+ "scope_kind",
+ "email",
+ )
+ with op.batch_alter_table("remote_access_authorizations") as batch_op:
+ for name in removable:
+ if name in columns:
+ batch_op.drop_column(name)
+ batch_op.alter_column(
+ "expires_at",
+ existing_type=sa.Integer(),
+ nullable=False,
+ )
diff --git a/storage/migrations.py b/storage/migrations.py
index c28f11d7f..a2f5daed4 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -150,9 +150,15 @@ HEAD_ONLY_REQUIRED_COLUMNS = {
"remote_access_authorizations": {
"instance_id",
"subject",
+ "email",
+ "scope_kind",
+ "scope_ref",
+ "authorization_state",
"claims_json",
"expires_at",
"created_at",
+ "last_checked_at",
+ "updated_at",
},
"vault_requests": {"callback_status"},
"vault_grants": {"agent_ready", "agent_ready_at"},
diff --git a/storage/models.py b/storage/models.py
index c5ad99167..33672c881 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -155,10 +155,25 @@ remote_access_authorizations = Table(
Column("id", String, primary_key=True),
Column("instance_id", String, nullable=False),
Column("subject", String, nullable=False),
+ Column("email", String, nullable=True),
+ Column("scope_kind", String, nullable=True),
+ Column("scope_ref", String, nullable=True),
+ Column("authorization_state", String, nullable=True),
Column("claims_json", Text, nullable=False),
- Column("expires_at", Integer, nullable=False),
+ Column("expires_at", Integer, nullable=True),
Column("created_at", Integer, nullable=False),
+ Column("last_checked_at", Integer, nullable=True),
+ Column("updated_at", Integer, nullable=True),
Index("ix_remote_access_authorizations_expires", "expires_at"),
+ Index(
+ "ux_remote_access_authorizations_scope",
+ "instance_id",
+ "subject",
+ "scope_kind",
+ "scope_ref",
+ unique=True,
+ sqlite_where=text("scope_kind is not null and scope_ref is not null"),
+ ),
)
auth_codes = Table(
diff --git a/storage/remote_access_authorization_service.py b/storage/remote_access_authorization_service.py
index f0d394191..c197357cb 100644
--- a/storage/remote_access_authorization_service.py
+++ b/storage/remote_access_authorization_service.py
@@ -1,11 +1,13 @@
-"""Short-lived server-side storage for remote organization authorization claims."""
+"""Durable current authorization plus legacy short-lived claims references."""
from __future__ import annotations
import json
+import secrets
from typing import Any, Mapping
-from sqlalchemy import select
+from sqlalchemy import and_, or_, select, update
+from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from storage.db import get_cached_sqlite_engine
from storage.models import remote_access_authorizations
@@ -42,7 +44,37 @@ def store(
)
-def load(
+def _decode_claims(value: Any) -> dict[str, Any] | None:
+ if not isinstance(value, str):
+ return None
+ try:
+ claims = json.loads(value)
+ except (TypeError, ValueError):
+ return None
+ return claims if isinstance(claims, dict) else None
+
+
+def _record_from_row(row: Any) -> dict[str, Any] | None:
+ claims = _decode_claims(row.claims_json)
+ if claims is None:
+ return None
+ return {
+ "id": row.id,
+ "instance_id": row.instance_id,
+ "subject": row.subject,
+ "email": row.email,
+ "scope_kind": row.scope_kind,
+ "scope_ref": row.scope_ref,
+ "authorization_state": row.authorization_state,
+ "claims": claims,
+ "expires_at": row.expires_at,
+ "created_at": row.created_at,
+ "last_checked_at": row.last_checked_at,
+ "updated_at": row.updated_at,
+ }
+
+
+def load_reference_record(
*,
reference: str,
instance_id: str,
@@ -51,17 +83,212 @@ def load(
) -> dict[str, Any] | None:
engine = get_cached_sqlite_engine()
with engine.connect() as conn:
- value = conn.execute(
- select(remote_access_authorizations.c.claims_json)
+ row = conn.execute(
+ select(remote_access_authorizations)
.where(remote_access_authorizations.c.id == reference)
.where(remote_access_authorizations.c.instance_id == instance_id)
.where(remote_access_authorizations.c.subject == subject)
- .where(remote_access_authorizations.c.expires_at > now)
+ .where(
+ or_(
+ remote_access_authorizations.c.scope_kind.is_not(None),
+ remote_access_authorizations.c.expires_at > now,
+ )
+ )
+ ).one_or_none()
+ return _record_from_row(row) if row is not None else None
+
+
+def load(
+ *,
+ reference: str,
+ instance_id: str,
+ subject: str,
+ now: int,
+) -> dict[str, Any] | None:
+ record = load_reference_record(
+ reference=reference,
+ instance_id=instance_id,
+ subject=subject,
+ now=now,
+ )
+ return record["claims"] if record is not None else None
+
+
+def load_scoped(
+ *,
+ instance_id: str,
+ subject: str,
+ scope_kind: str,
+ scope_ref: str,
+) -> dict[str, Any] | None:
+ engine = get_cached_sqlite_engine()
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(remote_access_authorizations)
+ .where(remote_access_authorizations.c.instance_id == instance_id)
+ .where(remote_access_authorizations.c.subject == subject)
+ .where(remote_access_authorizations.c.scope_kind == scope_kind)
+ .where(remote_access_authorizations.c.scope_ref == scope_ref)
+ ).one_or_none()
+ return _record_from_row(row) if row is not None else None
+
+
+def upsert_scoped(
+ *,
+ reference: str | None,
+ instance_id: str,
+ subject: str,
+ email: str,
+ scope_kind: str,
+ scope_ref: str,
+ authorization_state: str,
+ claims: Mapping[str, Any],
+ last_checked_at: int,
+ updated_at: int,
+) -> str:
+ """Store one current Instance or Show Page context without expiring it."""
+
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+ reference = reference or secrets.token_urlsafe(24)
+ values = {
+ "id": reference,
+ "instance_id": instance_id,
+ "subject": subject,
+ "email": email,
+ "scope_kind": scope_kind,
+ "scope_ref": scope_ref,
+ "authorization_state": authorization_state,
+ "claims_json": json.dumps(dict(claims), separators=(",", ":"), sort_keys=True),
+ "expires_at": None,
+ "created_at": updated_at,
+ "last_checked_at": last_checked_at,
+ "updated_at": updated_at,
+ }
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as conn:
+ existing_scope_reference = conn.execute(
+ select(remote_access_authorizations.c.id)
+ .where(remote_access_authorizations.c.instance_id == instance_id)
+ .where(remote_access_authorizations.c.subject == subject)
+ .where(remote_access_authorizations.c.scope_kind == scope_kind)
+ .where(remote_access_authorizations.c.scope_ref == scope_ref)
).scalar_one_or_none()
- if not isinstance(value, str):
- return None
- try:
- claims = json.loads(value)
- except (TypeError, ValueError):
- return None
- return claims if isinstance(claims, dict) else None
+ if existing_scope_reference is not None:
+ conn.execute(
+ update(remote_access_authorizations)
+ .where(remote_access_authorizations.c.id == existing_scope_reference)
+ .values(
+ email=email,
+ authorization_state=authorization_state,
+ claims_json=values["claims_json"],
+ expires_at=None,
+ last_checked_at=last_checked_at,
+ updated_at=updated_at,
+ )
+ )
+ return str(existing_scope_reference)
+
+ # A released cookie may still point at a random-reference row. Promote
+ # that exact row on its first successful refresh so the cookie remains
+ # valid and the new durable scope does not collide with its primary key.
+ legacy_reference = conn.execute(
+ select(
+ remote_access_authorizations.c.instance_id,
+ remote_access_authorizations.c.subject,
+ remote_access_authorizations.c.scope_kind,
+ ).where(remote_access_authorizations.c.id == reference)
+ ).one_or_none()
+ if (
+ legacy_reference is not None
+ and legacy_reference.instance_id == instance_id
+ and legacy_reference.subject == subject
+ and legacy_reference.scope_kind is None
+ ):
+ conn.execute(
+ update(remote_access_authorizations)
+ .where(remote_access_authorizations.c.id == reference)
+ .values(**{key: value for key, value in values.items() if key != "id"})
+ )
+ return reference
+ if legacy_reference is not None:
+ reference = secrets.token_urlsafe(24)
+ values["id"] = reference
+
+ statement = sqlite_insert(remote_access_authorizations).values(**values)
+ statement = statement.on_conflict_do_update(
+ index_elements=[
+ remote_access_authorizations.c.instance_id,
+ remote_access_authorizations.c.subject,
+ remote_access_authorizations.c.scope_kind,
+ remote_access_authorizations.c.scope_ref,
+ ],
+ index_where=and_(
+ remote_access_authorizations.c.scope_kind.is_not(None),
+ remote_access_authorizations.c.scope_ref.is_not(None),
+ ),
+ set_={
+ "email": email,
+ "authorization_state": authorization_state,
+ "claims_json": values["claims_json"],
+ "expires_at": None,
+ "last_checked_at": last_checked_at,
+ "updated_at": updated_at,
+ },
+ )
+ conn.execute(statement)
+ stored_reference = conn.execute(
+ select(remote_access_authorizations.c.id)
+ .where(remote_access_authorizations.c.instance_id == instance_id)
+ .where(remote_access_authorizations.c.subject == subject)
+ .where(remote_access_authorizations.c.scope_kind == scope_kind)
+ .where(remote_access_authorizations.c.scope_ref == scope_ref)
+ ).scalar_one()
+ return str(stored_reference)
+
+
+def mark_matching_revision_checked(
+ *,
+ instance_id: str,
+ authorization_revision: int,
+ checked_at: int,
+) -> int:
+ """Extend outage grace only for contexts matching a fresh device watermark."""
+
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as conn:
+ rows = conn.execute(
+ select(
+ remote_access_authorizations.c.id,
+ remote_access_authorizations.c.claims_json,
+ )
+ .where(remote_access_authorizations.c.instance_id == instance_id)
+ .where(remote_access_authorizations.c.scope_kind.is_not(None))
+ .where(remote_access_authorizations.c.authorization_state == "current")
+ ).all()
+ matching_ids = []
+ for row in rows:
+ claims = _decode_claims(row.claims_json)
+ revision = claims.get("vibe_instance_authorization_revision") if claims else None
+ if isinstance(revision, int) and not isinstance(revision, bool) and revision == authorization_revision:
+ matching_ids.append(row.id)
+ if not matching_ids:
+ return 0
+ result = conn.execute(
+ update(remote_access_authorizations)
+ .where(remote_access_authorizations.c.id.in_(matching_ids))
+ .values(last_checked_at=checked_at, updated_at=checked_at)
+ )
+ return int(result.rowcount or 0)
+
+
+def delete_for_instance(instance_id: str) -> int:
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as conn:
+ result = conn.execute(
+ remote_access_authorizations.delete().where(
+ remote_access_authorizations.c.instance_id == instance_id
+ )
+ )
+ return int(result.rowcount or 0)
diff --git a/storage/web_push_service.py b/storage/web_push_service.py
index ed1b53e47..d35f0c723 100644
--- a/storage/web_push_service.py
+++ b/storage/web_push_service.py
@@ -215,6 +215,34 @@ def disable_subscription(conn: Connection, *, endpoint: str, user_key: str | Non
return bool(result.rowcount)
+def disable_device_subscription(
+ conn: Connection,
+ *,
+ user_key: str,
+ device_id: str | None = None,
+ endpoint: str | None = None,
+) -> bool:
+ """Disable only the logging-out browser's selected Push subscription."""
+
+ device_id = device_id.strip() if isinstance(device_id, str) else ""
+ endpoint = endpoint.strip() if isinstance(endpoint, str) else ""
+ if not device_id and not endpoint:
+ return False
+ stmt = (
+ web_push_subscriptions.update()
+ .where(web_push_subscriptions.c.user_key == user_key)
+ .where(web_push_subscriptions.c.enabled == 1)
+ )
+ if endpoint:
+ stmt = stmt.where(web_push_subscriptions.c.endpoint == endpoint)
+ else:
+ stmt = stmt.where(web_push_subscriptions.c.device_id == device_id)
+ result = conn.execute(
+ stmt.values(enabled=0, updated_at=_utc_now_iso())
+ )
+ return bool(result.rowcount)
+
+
def count_enabled(conn: Connection, *, user_key: str | None = None) -> int:
stmt = select(func.count()).select_from(web_push_subscriptions).where(web_push_subscriptions.c.enabled == 1)
if user_key is not None:
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 5bb646e89..144c5ed99 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -246,6 +246,20 @@ scenarios:
layer: scenario
backend: show_page_email
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::ShowPageEmailAccessScenarioTests::test_exact_email_login_is_confined_to_its_signed_show_page
+ - id: AUTH-SETUP-402
+ name: Personal remote activity slides past the original identity deadline without another authorization prompt
+ status: covered
+ kind: happy_path
+ layer: scenario
+ backend: web
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_personal_remote_session_slides_without_interactive_reauthorization
+ - id: AUTH-SETUP-403
+ name: Organization remote access enters grace, recovers silently, and enforces confirmed revocation without OAuth
+ status: covered
+ kind: authorization
+ layer: scenario
+ backend: web
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_organization_remote_session_recovers_and_revokes_without_oauth
- id: AUTH-SETUP-210
name: Lost Model Hub OAuth start response converges on one provider flow
status: covered
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 1d06ed7b3..0ad528c7e 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -3,6 +3,7 @@ import json
import os
import sys
import tempfile
+import time
import unittest
import urllib.parse
from concurrent.futures import ThreadPoolExecutor
@@ -41,6 +42,7 @@ from tests.scenario_harness.organization_management import (
OrganizationManagementScenarioHarness,
)
from tests.scenario_harness.show_page_email_access import ShowPageEmailAccessScenarioHarness
+from storage import remote_access_authorization_service
from vibe import cloud_management
from tests.scenario_harness.model_hub_native_oauth import (
HubOAuthScenarioHarness,
@@ -632,6 +634,190 @@ def test_remote_web_oauth_cold_launch_retry_is_single_owner(monkeypatch, tmp_pat
)
+def _save_remote_session_authorization_config(instance_kind: str) -> V2Config:
+ config = _save_remote_web_auth_config()
+ cloud = config.remote_access.vibe_cloud
+ cloud.backend_url = "https://backend.test"
+ cloud.instance_secret = "device-secret"
+ cloud.instance_kind = instance_kind
+ config.save()
+ remote_access._clear_authorization_revision_cache()
+ remote_access._replace_authorization_revision(config, 1)
+ return config
+
+
+def test_personal_remote_session_slides_without_interactive_reauthorization(
+ monkeypatch,
+ tmp_path,
+):
+ """Scenario: AUTH-SETUP-402."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_remote_session_authorization_config("personal")
+ base = int(time.time())
+ harness = SimpleNamespace(config=config, cookie=None, payload=None)
+ runner = ScenarioRunner(harness)
+
+ def sign_in_once(current):
+ monkeypatch.setattr(remote_access.time, "time", lambda: base)
+ current.cookie = remote_access.make_session_cookie(
+ current.config,
+ "owner-1",
+ session_claims={
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "owner",
+ "vibe_instance_access_source": "owner",
+ "vibe_instance_authorization_revision": 1,
+ },
+ )
+
+ def slide_after_half_life(current):
+ monkeypatch.setattr(
+ remote_access.time,
+ "time",
+ lambda: base + remote_access.PERSONAL_SESSION_RENEW_AFTER_SECONDS + 1,
+ )
+ identity = remote_access.parse_session_identity(current.config, current.cookie)
+ assert identity is not None
+ resolution = remote_access.resolve_current_authorization(current.config, identity)
+ assert resolution.current is True
+ current.cookie = remote_access.renew_session_cookie(current.config, resolution.payload)
+
+ def continue_after_original_expiry(current):
+ monkeypatch.setattr(
+ remote_access.time,
+ "time",
+ lambda: base + remote_access.PERSONAL_SESSION_TTL_SECONDS + 60,
+ )
+ identity = remote_access.parse_session_identity(current.config, current.cookie)
+ assert identity is not None
+ resolution = remote_access.resolve_current_authorization(current.config, identity)
+ assert resolution.current is True
+ assert resolution.policy == "personal"
+ assert resolution.payload["claims_issued_at"] == base
+
+ asyncio.run(
+ runner.run(
+ ScenarioStep("sign_in_once", sign_in_once),
+ ScenarioStep("slide_after_half_life", slide_after_half_life),
+ ScenarioStep("continue_after_original_expiry", continue_after_original_expiry),
+ )
+ )
+ ScenarioExpect.step_history(
+ runner,
+ ["sign_in_once", "slide_after_half_life", "continue_after_original_expiry"],
+ )
+
+
+def test_organization_remote_session_recovers_and_revokes_without_oauth(
+ monkeypatch,
+ tmp_path,
+):
+ """Scenario: AUTH-SETUP-403."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_remote_session_authorization_config("organization")
+ mode = {"value": "unavailable", "revision": 2}
+
+ def device_request(_config, method, suffix, payload=None, *, timeout=8.0):
+ assert (method, suffix, timeout) == ("POST", "authorization-context", 8.0)
+ if mode["value"] == "unavailable":
+ raise remote_access.BackendRequestError(503, {"error": "unavailable"})
+ if mode["value"] == "revoked":
+ raise remote_access.BackendRequestError(403, {"error": "access_denied"})
+ return {
+ "sub": payload["sub"],
+ "email": payload["email"],
+ "instance_kind": "organization",
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_instance_authorization_revision": mode["revision"],
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "member-1",
+ "vibe_organization_role": "member",
+ "vibe_group_ids": ["group-1"],
+ "vibe_membership_version": f"v{mode['revision']}",
+ }
+
+ monkeypatch.setattr(remote_access, "_device_json_request", device_request)
+ cookie = remote_access.make_session_cookie(
+ config,
+ "member-1",
+ session_claims={
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_instance_authorization_revision": 1,
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "member-1",
+ "vibe_organization_role": "member",
+ "vibe_group_ids": ["group-1"],
+ "vibe_membership_version": "v1",
+ },
+ )
+ client = app.test_client()
+ client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")
+ harness = SimpleNamespace(config=config, client=client)
+ runner = ScenarioRunner(harness)
+
+ def enter_control_plane_grace(current):
+ now = int(time.time())
+ assert remote_access_authorization_service.mark_matching_revision_checked(
+ instance_id="inst_123",
+ authorization_revision=1,
+ checked_at=now,
+ ) == 1
+ remote_access._replace_authorization_revision(current.config, 2)
+ session = current.client.get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ ).get_json()
+ assert session["authenticated"] is True
+ assert session["authorization_state"] == "current"
+
+ def recover_silently(current):
+ remote_access._AUTHORIZATION_REFRESH_FAILURES.clear()
+ mode["value"] = "current"
+ session = current.client.get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ ).get_json()
+ assert session["authenticated"] is True
+ assert session["authorization_state"] == "current"
+ assert session["instance_role"] == "editor"
+
+ def enforce_confirmed_revocation(current):
+ mode.update(value="revoked", revision=3)
+ remote_access._replace_authorization_revision(current.config, 3)
+ protected = current.client.get(
+ "/api/config",
+ base_url="https://alex.avibe.bot",
+ )
+ session = current.client.get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ ).get_json()
+ assert protected.status_code == 403
+ assert protected.get_json()["error"] == "remote_access_revoked"
+ assert session["authenticated"] is True
+ assert session["authorization_state"] == "revoked"
+
+ asyncio.run(
+ runner.run(
+ ScenarioStep("enter_control_plane_grace", enter_control_plane_grace),
+ ScenarioStep("recover_silently", recover_silently),
+ ScenarioStep("enforce_confirmed_revocation", enforce_confirmed_revocation),
+ )
+ )
+ ScenarioExpect.step_history(
+ runner,
+ ["enter_control_plane_grace", "recover_silently", "enforce_confirmed_revocation"],
+ )
+
+
class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
async def test_claude_oauth_to_explicit_auth_token_reaches_next_turn(self):
"""Scenario: AUTH-SETUP-904"""
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index bb79b104d..dd6ed4d98 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -2758,8 +2758,9 @@ def test_cloud_token_for_request_returns_none_without_valid_session(monkeypatch)
assert remote_access.cloud_token_for_request(config, "bogus.cookie") is None
-def test_cloud_token_for_request_rejects_stale_authorization_claims(monkeypatch) -> None:
+def test_cloud_token_for_request_uses_shared_personal_authorization_policy(monkeypatch) -> None:
config = _cloud_broker_config()
+ config.remote_access.vibe_cloud.instance_kind = "personal"
monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *a, **k: 1)
cookie = _session_cookie(config)
called = False
@@ -2776,8 +2777,8 @@ def test_cloud_token_for_request_rejects_stale_authorization_claims(monkeypatch)
lambda payload: True,
)
- assert remote_access.cloud_token_for_request(config, cookie) is None
- assert called is False
+ assert remote_access.cloud_token_for_request(config, cookie) is not None
+ assert called is True
def test_cloud_token_for_request_requires_editor_role(monkeypatch) -> None:
diff --git a/tests/test_remote_authorization_revision.py b/tests/test_remote_authorization_revision.py
index 9c803e6b9..cdfe0104d 100644
--- a/tests/test_remote_authorization_revision.py
+++ b/tests/test_remote_authorization_revision.py
@@ -1,6 +1,8 @@
from __future__ import annotations
import asyncio
+from concurrent.futures import ThreadPoolExecutor
+import threading
import time
from typing import Any
@@ -16,12 +18,28 @@ from config.v2_config import (
V2Config,
)
from tests.ui_server_test_helpers import csrf_headers
+from storage import remote_access_authorization_service
from vibe import remote_access, ui_server
from vibe.authorization import context_from_session_payload
from vibe.ui_compat import g
from vibe.ui_server import app
[email protected](autouse=True)
+def _clear_authorization_refresh_process_state():
+ with remote_access._AUTHORIZATION_REFRESH_LOCK:
+ remote_access._AUTHORIZATION_REFRESH_FAILURES.clear()
+ remote_access._AUTHORIZATION_REFRESH_RESULTS.clear()
+ remote_access._AUTHORIZATION_REFRESH_FLIGHTS.clear()
+ with remote_access._AUTHORIZATION_BACKGROUND_REFRESH_LOCK:
+ remote_access._AUTHORIZATION_BACKGROUND_REFRESHES.clear()
+ yield
+ with remote_access._AUTHORIZATION_REFRESH_LOCK:
+ remote_access._AUTHORIZATION_REFRESH_FAILURES.clear()
+ remote_access._AUTHORIZATION_REFRESH_RESULTS.clear()
+ remote_access._AUTHORIZATION_REFRESH_FLIGHTS.clear()
+
+
def _paired_config(tmp_path, *, revision: int = 41) -> V2Config:
config = V2Config(
mode="self_host",
@@ -40,6 +58,7 @@ def _paired_config(tmp_path, *, revision: int = 41) -> V2Config:
cloud.public_url = "https://alex.avibe.bot"
cloud.client_id = "vr_client_123"
cloud.instance_id = "inst_123"
+ cloud.instance_kind = "organization"
cloud.instance_secret = "instance-secret"
cloud.session_secret = "session-secret"
cloud.authorization_endpoint = "https://backend.test/oauth/authorize"
@@ -83,6 +102,750 @@ def _organization_cookie(
)
+def _authorization_context_response(
+ config: V2Config,
+ request_payload: dict[str, Any],
+ *,
+ revision: int,
+ instance_kind: str = "organization",
+) -> dict[str, Any]:
+ return {
+ "sub": request_payload["sub"],
+ "email": request_payload["email"],
+ "instance_kind": instance_kind,
+ **_organization_claims(config, revision=revision),
+ }
+
+
+def test_personal_session_slides_past_claim_and_original_identity_deadlines(
+ monkeypatch,
+ tmp_path,
+):
+ """Scenario: AUTH-SETUP-402."""
+
+ config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
+ base = int(time.time())
+ monkeypatch.setattr(remote_access.time, "time", lambda: base)
+ cookie = remote_access.make_session_cookie(
+ config,
+ "personal-owner",
+ session_claims={
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "owner",
+ "vibe_instance_access_source": "owner",
+ "vibe_instance_authorization_revision": 41,
+ },
+ )
+
+ monkeypatch.setattr(
+ remote_access.time,
+ "time",
+ lambda: base + remote_access.PERSONAL_SESSION_RENEW_AFTER_SECONDS + 1,
+ )
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ first = remote_access.resolve_current_authorization(config, identity)
+ assert first.current is True
+ renewed_cookie = remote_access.renew_session_cookie(config, first.payload)
+ renewed_identity = remote_access.parse_session_identity(config, renewed_cookie)
+ assert renewed_identity is not None
+ assert renewed_identity["claims_issued_at"] == base
+
+ monkeypatch.setattr(
+ remote_access.time,
+ "time",
+ lambda: base + remote_access.PERSONAL_SESSION_TTL_SECONDS + 60,
+ )
+ after_original_expiry = remote_access.parse_session_identity(config, renewed_cookie)
+ assert after_original_expiry is not None
+ result = remote_access.resolve_current_authorization(config, after_original_expiry)
+ assert result.current is True
+ assert result.policy == "personal"
+ assert result.payload["claims_issued_at"] == base
+
+
+def test_personal_revision_hint_refreshes_in_background_without_blocking(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ entered = threading.Event()
+ release = threading.Event()
+ finished = threading.Event()
+
+ def unavailable(*args, **kwargs):
+ entered.set()
+ release.wait(timeout=1)
+ finished.set()
+ raise remote_access.BackendRequestError(503, {"error": "unavailable"})
+
+ monkeypatch.setattr(remote_access, "_device_json_request", unavailable)
+
+ result = remote_access.resolve_current_authorization(config, identity)
+
+ assert result.current is True
+ assert result.policy == "personal"
+ assert entered.wait(timeout=1)
+ assert finished.is_set() is False
+ release.set()
+ assert finished.wait(timeout=1)
+
+
+def test_organization_scheduled_refresh_does_not_block_when_revision_matches(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ base = int(time.time())
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ refresh_at = base + remote_access.ORGANIZATION_AUTHORIZATION_REFRESH_SECONDS + 1
+ assert remote_access_authorization_service.mark_matching_revision_checked(
+ instance_id="inst_123",
+ authorization_revision=41,
+ checked_at=refresh_at,
+ ) == 1
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 41)
+ scheduled = []
+ monkeypatch.setattr(
+ remote_access,
+ "_schedule_authorization_refresh",
+ lambda *args, **kwargs: scheduled.append((args, kwargs)),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_refresh_authorization_context",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("routine matching-revision refresh blocked the request")
+ ),
+ )
+
+ result = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ now=refresh_at,
+ )
+
+ assert result.current is True
+ assert result.policy == "organization"
+ assert result.reason == "authorization_refresh_scheduled"
+ assert len(scheduled) == 1
+
+
+def test_organization_refresh_grace_expiry_and_recovery(monkeypatch, tmp_path):
+ """Scenario: AUTH-SETUP-403."""
+
+ config = _paired_config(tmp_path)
+ base = int(time.time())
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ checked_at = base + remote_access.ORGANIZATION_AUTHORIZATION_REFRESH_SECONDS
+ assert remote_access_authorization_service.mark_matching_revision_checked(
+ instance_id="inst_123",
+ authorization_revision=41,
+ checked_at=checked_at,
+ ) == 1
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(503, {"error": "unavailable"})
+ ),
+ )
+
+ within_grace = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ now=checked_at + 1,
+ )
+ assert within_grace.current is True
+ assert within_grace.reason == "authorization_grace"
+
+ remote_access._AUTHORIZATION_REFRESH_FAILURES.clear()
+ after_grace = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ now=checked_at + remote_access.ORGANIZATION_AUTHORIZATION_OUTAGE_GRACE_SECONDS + 1,
+ )
+ assert after_grace.state == "unavailable"
+ assert after_grace.reason == "authorization_grace_expired"
+
+ remote_access._AUTHORIZATION_REFRESH_FAILURES.clear()
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda _config, _method, _suffix, payload, **kwargs: _authorization_context_response(
+ config,
+ payload,
+ revision=42,
+ ),
+ )
+ recovered = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ now=checked_at + remote_access.ORGANIZATION_AUTHORIZATION_OUTAGE_GRACE_SECONDS + 2,
+ )
+ assert recovered.current is True
+ assert recovered.refreshed is True
+ assert recovered.payload["vibe_instance_authorization_revision"] == 42
+
+
+def test_unknown_instance_kind_backfills_without_failing_valid_access(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = ""
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda _config, _method, _suffix, payload, **kwargs: _authorization_context_response(
+ config,
+ payload,
+ revision=42,
+ ),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_persist_instance_kind",
+ lambda *args, **kwargs: (_ for _ in ()).throw(OSError("read-only config")),
+ )
+
+ result = remote_access.resolve_current_authorization(config, identity)
+
+ assert result.current is True
+ assert result.policy == "organization"
+ assert config.remote_access.vibe_cloud.instance_kind == "organization"
+
+
+def test_scoped_authorization_promotes_legacy_rows_and_isolates_show_pages(tmp_path):
+ now = int(time.time())
+ remote_access_authorization_service.store(
+ reference="legacy-reference-12345678",
+ instance_id="inst_123",
+ subject="user-1",
+ claims={"vibe_instance_id": "inst_123"},
+ expires_at=now + 60,
+ created_at=now,
+ )
+
+ instance_reference = remote_access_authorization_service.upsert_scoped(
+ reference="legacy-reference-12345678",
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind="instance",
+ scope_ref="inst_123",
+ authorization_state="current",
+ claims={"scope": "instance"},
+ last_checked_at=now + 1,
+ updated_at=now + 1,
+ )
+ show_reference = remote_access_authorization_service.upsert_scoped(
+ reference=None,
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind="show_page",
+ scope_ref="show-1",
+ authorization_state="current",
+ claims={"scope": "show_page"},
+ last_checked_at=now + 2,
+ updated_at=now + 2,
+ )
+
+ instance = remote_access_authorization_service.load_scoped(
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind="instance",
+ scope_ref="inst_123",
+ )
+ show_page = remote_access_authorization_service.load_scoped(
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind="show_page",
+ scope_ref="show-1",
+ )
+ assert instance_reference == "legacy-reference-12345678"
+ assert show_reference != instance_reference
+ assert instance is not None and instance["claims"] == {"scope": "instance"}
+ assert instance["expires_at"] is None
+ assert show_page is not None and show_page["claims"] == {"scope": "show_page"}
+
+
+def test_referenced_identity_does_not_guess_scope_when_record_is_missing(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ cookie = remote_access.make_session_cookie(
+ config,
+ "viewer-1",
+ session_claims={
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": "show-1",
+ "vibe_instance_authorization_revision": 41,
+ },
+ )
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ assert isinstance(identity.get("authorization_ref"), str)
+ assert remote_access_authorization_service.delete_for_instance("inst_123") == 1
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("missing referenced records must not guess a refresh scope")
+ ),
+ )
+
+ result = remote_access.resolve_current_authorization(config, identity)
+
+ assert result.state == "invalid_identity"
+ assert result.reason == "authorization_record_missing"
+
+
+def test_authorization_record_read_failure_is_unavailable(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ monkeypatch.setattr(
+ remote_access_authorization_service,
+ "load_reference_record",
+ lambda **kwargs: (_ for _ in ()).throw(OSError("database unavailable")),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("storage failure must not trigger an unscoped refresh")
+ ),
+ )
+
+ result = remote_access.resolve_current_authorization(config, identity)
+
+ assert result.state == "unavailable"
+ assert result.reason == "authorization_record_unavailable"
+
+
+def test_revision_poll_touches_every_matching_current_context_only(tmp_path):
+ now = int(time.time())
+ rows = (
+ ("user-match", 7, "current"),
+ ("user-other", 8, "current"),
+ ("user-revoked", 7, "revoked"),
+ )
+ for subject, revision, state in rows:
+ remote_access_authorization_service.upsert_scoped(
+ reference=None,
+ instance_id="inst_123",
+ subject=subject,
+ email=f"{subject}@example.com",
+ scope_kind="instance",
+ scope_ref="inst_123",
+ authorization_state=state,
+ claims={"vibe_instance_authorization_revision": revision},
+ last_checked_at=now,
+ updated_at=now,
+ )
+
+ assert remote_access_authorization_service.mark_matching_revision_checked(
+ instance_id="inst_123",
+ authorization_revision=7,
+ checked_at=now + 30,
+ ) == 1
+ checked = {
+ subject: remote_access_authorization_service.load_scoped(
+ instance_id="inst_123",
+ subject=subject,
+ scope_kind="instance",
+ scope_ref="inst_123",
+ )["last_checked_at"]
+ for subject, _revision, _state in rows
+ }
+ assert checked == {
+ "user-match": now + 30,
+ "user-other": now,
+ "user-revoked": now,
+ }
+
+
+def test_concurrent_resolvers_share_one_authorization_context_refresh(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ calls = 0
+ calls_lock = threading.Lock()
+
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ nonlocal calls
+ with calls_lock:
+ calls += 1
+ time.sleep(0.05)
+ return _authorization_context_response(config, payload, revision=42)
+
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ results = list(executor.map(
+ lambda _index: remote_access.resolve_current_authorization(config, identity),
+ range(2),
+ ))
+
+ assert calls == 1
+ assert all(result.current and result.refreshed for result in results)
+
+
+def test_authorization_context_refreshes_for_different_subjects_run_concurrently(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ identities = []
+ for subject in ("user-1", "user-2"):
+ identity = remote_access.parse_session_identity(
+ config,
+ _organization_cookie(config, subject=subject),
+ )
+ assert identity is not None
+ identities.append(identity)
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ entered = threading.Barrier(2)
+ refreshed_subjects = []
+ calls_lock = threading.Lock()
+
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ with calls_lock:
+ refreshed_subjects.append(payload["sub"])
+ entered.wait(timeout=2)
+ return _authorization_context_response(config, payload, revision=42)
+
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ results = list(executor.map(
+ lambda identity: remote_access.resolve_current_authorization(config, identity),
+ identities,
+ ))
+
+ assert set(refreshed_subjects) == {"user-1", "user-2"}
+ assert all(result.current and result.refreshed for result in results)
+
+
+def test_concurrent_revocation_refresh_is_reused_and_persisted(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ calls = 0
+ calls_lock = threading.Lock()
+
+ def revoke(*args, **kwargs):
+ nonlocal calls
+ with calls_lock:
+ calls += 1
+ time.sleep(0.05)
+ raise remote_access.BackendRequestError(403, {"error": "access_denied"})
+
+ monkeypatch.setattr(remote_access, "_device_json_request", revoke)
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ results = list(executor.map(
+ lambda _index: remote_access.resolve_current_authorization(config, identity),
+ range(2),
+ ))
+
+ assert calls == 1
+ assert all(result.state == "revoked" for result in results)
+ with remote_access._AUTHORIZATION_REFRESH_LOCK:
+ remote_access._AUTHORIZATION_REFRESH_RESULTS.clear()
+
+ persisted = remote_access.resolve_current_authorization(config, identity)
+
+ assert persisted.state == "revoked"
+ assert calls == 1
+
+
+def test_refresh_backoff_starts_when_the_network_request_finishes(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ monotonic_values = iter((100.0, 110.0, 110.1))
+ monkeypatch.setattr(remote_access.time, "monotonic", lambda: next(monotonic_values))
+ calls = 0
+
+ def unavailable(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ raise remote_access.BackendRequestError(503, {"error": "unavailable"})
+
+ monkeypatch.setattr(remote_access, "_device_json_request", unavailable)
+
+ remote_access.resolve_current_authorization(config, identity)
+ remote_access.resolve_current_authorization(config, identity)
+
+ assert calls == 1
+
+
+def test_revoked_authorization_recovers_after_revision_change(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
+ ),
+ )
+ assert remote_access.resolve_current_authorization(config, identity).state == "revoked"
+
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 43)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda _config, _method, _suffix, payload, **kwargs: _authorization_context_response(
+ config,
+ payload,
+ revision=43,
+ ),
+ )
+
+ recovered = remote_access.resolve_current_authorization(config, identity)
+
+ assert recovered.current is True
+ assert recovered.refreshed is True
+ assert recovered.payload["vibe_instance_authorization_revision"] == 43
+
+
+def test_explicit_login_can_revalidate_revoked_authorization(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ observed_revision = 42
+ monkeypatch.setattr(
+ remote_access,
+ "current_authorization_revision",
+ lambda *args, **kwargs: observed_revision,
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
+ ),
+ )
+ assert remote_access.resolve_current_authorization(config, identity).state == "revoked"
+
+ refresh_calls = 0
+
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ nonlocal refresh_calls
+ refresh_calls += 1
+ return _authorization_context_response(config, payload, revision=42)
+
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+ assert remote_access.resolve_current_authorization(config, identity).state == "revoked"
+
+ recovered = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ refresh_revoked=True,
+ )
+
+ assert recovered.current is True
+ assert recovered.refreshed is True
+ assert refresh_calls == 1
+
+
+def test_remote_login_forces_revoked_authorization_revalidation(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ refresh_flags = []
+
+ def resolve(_config, identity, **kwargs):
+ refresh_flags.append(kwargs.get("refresh_revoked"))
+ return remote_access.AuthorizationResolution("current", payload=identity)
+
+ monkeypatch.setattr(remote_access, "resolve_current_authorization", resolve)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ cookie,
+ domain="alex.avibe.bot",
+ )
+
+ response = client.get(
+ "/auth/login?next=/inbox",
+ base_url="https://alex.avibe.bot",
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 302
+ assert response.headers["Location"] == "/inbox"
+ assert refresh_flags[-1] is True
+ assert refresh_flags.count(True) == 1
+
+
+def test_browser_logout_invalidates_http_sse_and_websocket(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ payload = remote_access.parse_session_cookie(config, cookie)
+ assert identity is not None
+ assert payload is not None
+ assert remote_access.revoke_browser_session(identity) is True
+
+ client = app.test_client()
+ client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")
+ assert client.get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ ).get_json()["authenticated"] is False
+
+ monkeypatch.setattr(ui_server, "_AUTHORIZATION_REVISION_RECHECK_SECONDS", 0.001)
+
+ async def exercise() -> None:
+ with app.test_request_context(
+ "/api/events",
+ base_url="https://alex.avibe.bot",
+ headers={"Cookie": f"{remote_access.SESSION_COOKIE_NAME}={cookie}"},
+ ):
+ g.authorization_context = context_from_session_payload(payload)
+ g.remote_session_identity = identity
+ g.remote_session_payload = payload
+ response = await ui_server.workbench_events()
+ iterator = response.body_iterator.__aiter__()
+ try:
+ terminal = await asyncio.wait_for(iterator.__anext__(), timeout=1)
+ assert '"state":"invalid_identity"' in terminal
+ with pytest.raises(StopAsyncIteration):
+ await iterator.__anext__()
+ finally:
+ await iterator.aclose()
+ outcome = await asyncio.wait_for(
+ ui_server._wait_for_remote_session_authorization_loss(
+ config,
+ identity,
+ payload,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
+ ),
+ timeout=1,
+ )
+ assert outcome == "invalid_identity"
+
+ asyncio.run(exercise())
+
+
+def test_legacy_browser_logout_derives_a_stable_revocation_identity(tmp_path):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ legacy_payload = remote_access.parse_session_identity(config, cookie)
+ assert legacy_payload is not None
+ legacy_payload.pop("browser_session_id")
+ legacy_cookie = remote_access._encode_session_cookie(
+ config.remote_access.vibe_cloud.session_secret,
+ legacy_payload,
+ )
+ accepted_identity = remote_access.parse_session_identity(config, legacy_cookie)
+ assert accepted_identity is not None
+ assert accepted_identity["browser_session_id"] == remote_access.parse_session_identity(
+ config,
+ legacy_cookie,
+ )["browser_session_id"]
+
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ legacy_cookie,
+ domain="alex.avibe.bot",
+ )
+ response = client.post(
+ "/auth/logout",
+ base_url="https://alex.avibe.bot",
+ json={},
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ )
+
+ assert response.status_code == 200
+ assert remote_access.parse_session_identity(config, legacy_cookie) is None
+ assert remote_access.session_identity_is_current(accepted_identity) is False
+
+
+ ("state", "status_code", "error"),
+ [
+ ("revoked", 403, "remote_access_revoked"),
+ ("unavailable", 503, "remote_access_authorization_unavailable"),
+ ],
+)
+def test_remote_authorization_failure_serves_spa_shell_but_rejects_api(
+ monkeypatch,
+ tmp_path,
+ state,
+ status_code,
+ error,
+):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ monkeypatch.setattr(
+ remote_access,
+ "resolve_current_authorization",
+ lambda *args, **kwargs: remote_access.AuthorizationResolution(state),
+ )
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ cookie,
+ domain="alex.avibe.bot",
+ )
+
+ shell = client.get(
+ "/",
+ base_url="https://alex.avibe.bot",
+ headers={"Accept": "text/html"},
+ )
+ protected = client.get(
+ "/api/config",
+ base_url="https://alex.avibe.bot",
+ headers={"Accept": "application/json"},
+ )
+
+ assert shell.status_code == 200
+ assert shell.headers["content-type"].startswith("text/html")
+ assert protected.status_code == status_code
+ assert protected.get_json()["error"] == error
+
+
def test_authorization_revision_device_contract_is_monotonic(monkeypatch, tmp_path):
"""I1057-AC2/AC3: one paired-device watermark drives every hostname."""
@@ -177,6 +940,13 @@ def test_revision_advance_revokes_active_editor_http_session(
assert before.status_code == 400
assert hosted_change
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
+ ),
+ )
remote_access._replace_authorization_revision(config, 42)
after = client.post(
"/api/sessions",
@@ -185,8 +955,8 @@ def test_revision_advance_revokes_active_editor_http_session(
json={},
)
- assert after.status_code == 401
- assert after.get_json()["error"] == "remote_access_login_required"
+ assert after.status_code == 403
+ assert after.get_json()["error"] == "remote_access_revoked"
def test_default_and_custom_hostname_sessions_share_revision(monkeypatch, tmp_path):
@@ -217,16 +987,35 @@ def test_default_and_custom_hostname_sessions_share_revision(monkeypatch, tmp_pa
base_url="https://max.fileguard.io",
).get_json()["authenticated"] is True
+ refreshed_subjects = []
+
+ def refresh(_config, method, suffix, payload=None, *, timeout=8.0):
+ assert (method, suffix, timeout) == ("POST", "authorization-context", 8.0)
+ refreshed_subjects.append(payload["sub"])
+ return {
+ "sub": payload["sub"],
+ "email": payload["email"],
+ "instance_kind": "organization",
+ **_organization_claims(config, revision=42),
+ }
+
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
remote_access._replace_authorization_revision(config, 42)
- assert default_client.get(
+ default_session = default_client.get(
"/api/session",
base_url="https://alex.avibe.bot",
- ).get_json()["authenticated"] is False
- assert custom_client.get(
+ ).get_json()
+ custom_session = custom_client.get(
"/api/session",
base_url="https://max.fileguard.io",
- ).get_json()["authenticated"] is False
+ ).get_json()
+
+ assert default_session["authenticated"] is True
+ assert default_session["authorization_state"] == "current"
+ assert custom_session["authenticated"] is True
+ assert custom_session["authorization_state"] == "current"
+ assert refreshed_subjects == ["default-user", "custom-user"]
def test_revision_snapshot_expiry_and_renewal_fail_closed(monkeypatch, tmp_path):
@@ -268,7 +1057,9 @@ def test_workbench_and_show_sse_end_after_revision_change(monkeypatch, tmp_path)
config = _paired_config(tmp_path)
cookie = _organization_cookie(config)
payload = remote_access.parse_session_cookie(config, cookie)
+ identity = remote_access.parse_session_identity(config, cookie)
assert payload is not None
+ assert identity is not None
context = context_from_session_payload(payload)
class EmptyShowEventStore:
@@ -279,10 +1070,22 @@ def test_workbench_and_show_sse_end_after_revision_change(monkeypatch, tmp_path)
return None
monkeypatch.setattr(ui_server, "_show_session_event_store", EmptyShowEventStore)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
+ ),
+ )
async def exercise() -> None:
- with app.test_request_context("/api/events"):
+ with app.test_request_context(
+ "/api/events",
+ base_url="https://alex.avibe.bot",
+ headers={"Cookie": f"{remote_access.SESSION_COOKIE_NAME}={cookie}"},
+ ):
g.authorization_context = context
+ g.remote_session_identity = identity
g.remote_session_payload = payload
response = await ui_server.workbench_events()
iterator = response.body_iterator.__aiter__()
@@ -290,6 +1093,8 @@ def test_workbench_and_show_sse_end_after_revision_change(monkeypatch, tmp_path)
for _ in range(3):
await iterator.__anext__()
remote_access._replace_authorization_revision(config, 42)
+ terminal = await asyncio.wait_for(iterator.__anext__(), timeout=1)
+ assert '"state":"revoked"' in terminal
with pytest.raises(StopAsyncIteration):
await asyncio.wait_for(iterator.__anext__(), timeout=1)
finally:
@@ -300,11 +1105,16 @@ def test_workbench_and_show_sse_end_after_revision_change(monkeypatch, tmp_path)
"ses123",
after_id="show_evt_resume",
authorization_context=context,
+ remote_session_identity=identity,
remote_session_payload=payload,
+ remote_session_cookie=cookie,
+ remote_request_host="alex.avibe.bot",
remote_config=config,
)
show_iterator = show_response.body_iterator.__aiter__()
try:
+ terminal = await asyncio.wait_for(show_iterator.__anext__(), timeout=1)
+ assert '"state":"revoked"' in terminal
with pytest.raises(StopAsyncIteration):
await asyncio.wait_for(show_iterator.__anext__(), timeout=1)
finally:
@@ -328,33 +1138,136 @@ def test_websocket_reconnect_and_active_waiter_recheck_revision(monkeypatch, tmp
monkeypatch.setattr(ui_server, "_remote_access_host_allowed", lambda *args: True)
monkeypatch.setattr(ui_server, "_websocket_normalized_host", lambda *args: "alex.avibe.bot")
monkeypatch.setattr(ui_server, "_AUTHORIZATION_REVISION_RECHECK_SECONDS", 0.001)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
+ ),
+ )
payload = ui_server._remote_access_websocket_session_payload(websocket, config)
+ identity = remote_access.parse_session_identity(config, cookie)
assert payload is not None
+ assert identity is not None
async def exercise() -> None:
waiter = asyncio.create_task(
- ui_server._wait_for_remote_session_authorization_loss(config, payload)
+ ui_server._wait_for_remote_session_authorization_loss(
+ config,
+ identity,
+ payload,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
+ )
)
await asyncio.sleep(0)
remote_access._replace_authorization_revision(config, 42)
- await asyncio.wait_for(waiter, timeout=1)
+ assert await asyncio.wait_for(waiter, timeout=1) == "revoked"
asyncio.run(exercise())
assert ui_server._remote_access_websocket_session_payload(websocket, config) is None
-def test_terminal_websocket_rejects_stale_remote_session_before_accept(
+def test_remote_websocket_authorization_rejects_disabled_cloud(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ config.remote_access.vibe_cloud.enabled = False
+
+ class Socket:
+ cookies = {remote_access.SESSION_COOKIE_NAME: cookie}
+
+ monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)
+ monkeypatch.setattr(ui_server, "_remote_access_host_allowed", lambda *args: True)
+ monkeypatch.setattr(ui_server, "_websocket_normalized_host", lambda *args: "alex.avibe.bot")
+ monkeypatch.setattr(
+ remote_access,
+ "resolve_current_authorization_async",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("disabled remote socket reached the authorization resolver")
+ ),
+ )
+
+ identity, resolution = asyncio.run(
+ ui_server._remote_access_websocket_authorization(Socket(), config)
+ )
+
+ assert identity is None
+ assert resolution.state == "invalid_identity"
+ assert resolution.reason == "remote_access_disabled"
+
+
+def test_live_remote_authorization_rechecks_the_remote_entry_gate(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ monkeypatch.setattr(
+ remote_access,
+ "resolve_current_authorization_async",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("invalid live session reached the authorization resolver")
+ ),
+ )
+
+ config.remote_access.vibe_cloud.enabled = False
+ config.save()
+ disabled = asyncio.run(
+ ui_server._live_remote_authorization_resolution(
+ config,
+ identity,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
+ )
+ )
+ assert disabled.state == "invalid_identity"
+ assert disabled.reason == "remote_access_disabled"
+
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.session_secret = "rotated-session-secret"
+ config.save()
+ rotated = asyncio.run(
+ ui_server._live_remote_authorization_resolution(
+ config,
+ identity,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
+ )
+ )
+ assert rotated.state == "invalid_identity"
+ assert rotated.reason == "identity_invalid"
+
+ config.remote_access.vibe_cloud.session_secret = "session-secret"
+ config.remote_access.vibe_cloud.public_url = "https://other.avibe.bot"
+ config.save()
+ moved = asyncio.run(
+ ui_server._live_remote_authorization_resolution(
+ config,
+ identity,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
+ )
+ )
+ assert moved.state == "invalid_identity"
+ assert moved.reason == "remote_access_host_mismatch"
+
+
+def test_terminal_websocket_reports_stale_remote_session_after_accept(
monkeypatch,
tmp_path,
):
- """I1057-AC4: a stale remote terminal request is never accepted."""
+ """I1057-AC4: no terminal service starts before a state-specific close."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
class RecordingWebSocket:
client = None
+ headers = {"host": "alex.avibe.bot"}
query_params = {}
def __init__(self):
@@ -370,10 +1283,16 @@ def test_terminal_websocket_rejects_stale_remote_session_before_accept(
monkeypatch.setattr(ui_server, "_terminal_enabled", lambda: True)
monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)
monkeypatch.setattr(ui_server, "_terminal_origin_allowed", lambda socket: True)
- monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda *a, **k: True)
monkeypatch.setattr(ui_server, "_load_remote_access_config", lambda: config)
- monkeypatch.setattr(ui_server, "_remote_access_websocket_session_claims", lambda *a: None)
monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *a: False)
+ monkeypatch.setattr(
+ ui_server,
+ "_remote_access_websocket_authorization",
+ lambda *args, **kwargs: asyncio.sleep(
+ 0,
+ result=(None, remote_access.AuthorizationResolution("unavailable")),
+ ),
+ )
monkeypatch.setattr(
ui_server,
"get_terminal_service",
@@ -383,7 +1302,8 @@ def test_terminal_websocket_rejects_stale_remote_session_before_accept(
asyncio.run(ui_server.terminal_websocket(websocket, "test"))
assert websocket.calls == [
- ("close", ui_server._AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE),
+ ("accept", None),
+ ("close", ui_server._AUTHORIZATION_UNAVAILABLE_WEBSOCKET_CLOSE_CODE),
]
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index ef4d4a4a2..76025b1ab 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -31,7 +31,7 @@ from vibe.message_types import build_partial_index_predicate
pytestmark = pytest.mark.no_sqlite_template
-HEAD_REVISION = "20260812_0053"
+HEAD_REVISION = "20260815_0054"
MESSAGE_PARTIAL_INDEX_PREDICATES = {
"ix_messages_inbox_activity": (
"session_id is not null and type in "
@@ -56,6 +56,82 @@ def _index_sql(conn: sqlite3.Connection, name: str) -> str:
return str(row[0] or "")
+def test_remote_authorization_context_migration_preserves_legacy_rows_both_directions(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260812_0053")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into remote_access_authorizations (
+ id, instance_id, subject, claims_json, expires_at, created_at
+ ) values (?, ?, ?, ?, ?, ?)
+ """,
+ (
+ "legacy-auth-reference",
+ "inst-1",
+ "user-1",
+ '{"legacy":true}',
+ 200,
+ 100,
+ ),
+ )
+
+ run_migrations(db_path)
+ with sqlite3.connect(db_path) as conn:
+ legacy = conn.execute(
+ "select claims_json, expires_at, scope_kind from remote_access_authorizations "
+ "where id = 'legacy-auth-reference'"
+ ).fetchone()
+ conn.execute(
+ """
+ insert into remote_access_authorizations (
+ id, instance_id, subject, email, scope_kind, scope_ref,
+ authorization_state, claims_json, expires_at, created_at,
+ last_checked_at, updated_at
+ ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ "scoped-auth-reference",
+ "inst-1",
+ "user-1",
+ "instance",
+ "inst-1",
+ "current",
+ '{"current":true}',
+ None,
+ 101,
+ 101,
+ 101,
+ ),
+ )
+ assert legacy == ('{"legacy":true}', 200, None)
+
+ command.downgrade(migrations.alembic_config(db_path), "20260812_0053")
+ with sqlite3.connect(db_path) as conn:
+ rows = conn.execute(
+ "select id, claims_json, expires_at from remote_access_authorizations"
+ ).fetchall()
+ expires_column = next(
+ row for row in conn.execute("pragma table_info(remote_access_authorizations)")
+ if row[1] == "expires_at"
+ )
+ columns = {row[1] for row in conn.execute("pragma table_info(remote_access_authorizations)")}
+
+ assert rows == [("legacy-auth-reference", '{"legacy":true}', 200)]
+ assert expires_column[3] == 1
+ assert not {
+ "email",
+ "scope_kind",
+ "scope_ref",
+ "authorization_state",
+ "last_checked_at",
+ "updated_at",
+ } & columns
+
+
@pytest.mark.parametrize(
("index_name", "expected_predicate"),
tuple(MESSAGE_PARTIAL_INDEX_PREDICATES.items()),
diff --git a/tests/test_terminal_backend.py b/tests/test_terminal_backend.py
index 3d44a42e0..63e1b3bc7 100644
--- a/tests/test_terminal_backend.py
+++ b/tests/test_terminal_backend.py
@@ -1428,7 +1428,7 @@ def test_terminal_websocket_unsupported_accepts_before_policy_close(monkeypatch)
assert websocket.calls == [("accept", None), ("close", 1008)]
-def test_remote_terminal_websocket_closes_at_authorization_refresh(monkeypatch):
+def test_remote_terminal_websocket_closes_when_authorization_becomes_unavailable(monkeypatch):
from vibe import remote_access
class BlockingTerminalService:
@@ -1441,23 +1441,46 @@ def test_remote_terminal_websocket_closes_at_authorization_refresh(monkeypatch):
monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)
monkeypatch.setattr(ui_server, "_terminal_origin_allowed", lambda websocket: True)
- monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda websocket, **kwargs: True)
+ monkeypatch.setattr(ui_server, "_load_remote_access_config", V2Config.default)
+ monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)
+
+ async def authorize(*args, **kwargs):
+ payload = {
+ "email": "[email protected]",
+ "sub": "remote-owner",
+ "instance_id": "inst-1",
+ "iat": 1,
+ "exp": 4_102_444_800,
+ "vibe_instance_id": "inst-1",
+ "vibe_instance_role": "owner",
+ "vibe_instance_access_source": "owner",
+ }
+ return payload, remote_access.AuthorizationResolution("current", payload=payload)
+
+ async def authorization_loss(*args, **kwargs):
+ return "unavailable"
+
+ monkeypatch.setattr(
+ ui_server,
+ "_remote_access_websocket_authorization",
+ authorize,
+ )
monkeypatch.setattr(
ui_server,
- "_remote_access_websocket_session_claims",
- lambda websocket, config: {"sub": "remote-owner", "claims_issued_at": 1},
+ "_wait_for_remote_session_authorization_loss",
+ authorization_loss,
)
- monkeypatch.setattr(remote_access, "session_authorization_refresh_deadline", lambda payload: 0)
monkeypatch.setattr(ui_server, "get_terminal_service", lambda: BlockingTerminalService())
websocket = _RecordingWebSocket()
websocket.client = None
+ websocket.headers = {"host": "alex.avibe.bot"}
websocket.query_params = {}
asyncio.run(ui_server.terminal_websocket(websocket, "test"))
assert websocket.calls == [
("accept", None),
- ("close", ui_server._AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE),
+ ("close", ui_server._AUTHORIZATION_UNAVAILABLE_WEBSOCKET_CLOSE_CODE),
]
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 8b6ebae66..65b094a19 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -2654,25 +2654,30 @@ def test_workbench_events_allow_show_events_when_show_page_acl_allows(monkeypatc
assert "/private/host/path.png" not in body
-def test_workbench_events_end_at_authorization_refresh_deadline():
+def test_local_workbench_events_ignore_legacy_authorization_refresh_deadline():
from vibe.authorization import AuthorizationContext
+ from vibe.sse_broker import broker
from vibe.ui_compat import g
async def collect_until_expired() -> list[str | bytes]:
- with app.test_request_context("/api/events"):
- g.authorization_context = AuthorizationContext(instance_role="owner", is_remote=True)
- g.remote_authorization_refresh_at = ui_server.time.time()
- response = await ui_server.workbench_events()
- iterator = response.body_iterator.__aiter__()
- try:
- chunks = [await iterator.__anext__() for _ in range(3)]
- with pytest.raises(StopAsyncIteration):
- await asyncio.wait_for(iterator.__anext__(), timeout=1)
- finally:
- await iterator.aclose()
- return chunks
-
- assert len(asyncio.run(collect_until_expired())) == 3
+ with app.test_request_context("/api/events"):
+ g.authorization_context = AuthorizationContext(instance_role="owner", is_remote=True)
+ g.remote_authorization_refresh_at = ui_server.time.time()
+ response = await ui_server.workbench_events()
+ iterator = response.body_iterator.__aiter__()
+ try:
+ chunks = [await iterator.__anext__() for _ in range(3)]
+ next_chunk = asyncio.create_task(iterator.__anext__())
+ await asyncio.sleep(0)
+ broker.publish("authorization.changed", {"project_ids": []})
+ chunks.append(await asyncio.wait_for(next_chunk, timeout=1))
+ finally:
+ await iterator.aclose()
+ return chunks
+
+ chunks = asyncio.run(collect_until_expired())
+ assert len(chunks) == 4
+ assert "event: authorization.changed" in chunks[-1]
def test_json_api_gzip_skips_attachments_and_existing_encoding():
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index b6870b99d..d3d264cfc 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -352,14 +352,13 @@ def test_workbench_memory_text_is_persisted_and_dispatched_as_ordinary_input(
],
)
def test_remote_workbench_memory_identity_requires_a_stable_subject(session_payload, expected):
- from vibe import remote_access
from vibe.ui_server import app, _workbench_memory_user_id
with (
app.test_request_context("/chat/session", headers={"Cookie": "avibe_remote_session=session"}),
patch("vibe.ui_server.is_direct_loopback_memory_request", return_value=False),
patch("vibe.ui_server._load_remote_access_config", return_value=object()),
- patch.object(remote_access, "parse_session_cookie", return_value=session_payload),
+ patch("vibe.ui_server._resolved_remote_session_payload", return_value=session_payload),
):
assert _workbench_memory_user_id() == expected
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 8e0f97fab..95f7ca8f2 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -16,6 +16,7 @@ from types import SimpleNamespace
from unittest.mock import patch
import pytest
+from starlette.websockets import WebSocketDisconnect
from config import paths
from core.show_pages import (
@@ -3302,15 +3303,32 @@ def test_public_show_page_clears_show_event_write_cookie(monkeypatch, tmp_path):
assert "permissions-policy" not in response.headers
-def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch, tmp_path):
+def test_show_events_stream_replays_persisted_pages_with_batch_authorization_checks(
+ monkeypatch,
+ tmp_path,
+):
from core.show_session_events import ShowSessionEventStore
from vibe.authorization import instance_owner_context
from vibe.ui_server import _show_events_stream
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- _save_config(tmp_path)
+ config = _save_config(tmp_path)
_create_agent_session("ses123")
_create_show_page("ses123", "private")
+ cookie = _active_org_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ authorization_checks = []
+
+ async def _authorization_state(*args, **kwargs):
+ authorization_checks.append((args, kwargs))
+ return "current"
+
+ monkeypatch.setattr(
+ ui_server,
+ "_remote_stream_authorization_state",
+ _authorization_state,
+ )
store = ShowSessionEventStore()
try:
for index in range(501):
@@ -3333,6 +3351,11 @@ def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch,
response = await _show_events_stream(
"ses123",
authorization_context=instance_owner_context(),
+ remote_session_identity=identity,
+ remote_session_payload=identity,
+ remote_session_cookie=cookie,
+ remote_request_host="alex.avibe.bot",
+ remote_config=config,
)
iterator = response.body_iterator.__aiter__()
chunks = []
@@ -3352,6 +3375,7 @@ def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch,
assert "id: show_evt_500" in body
assert '"id": "show_evt_000"' in body
assert '"id": "show_evt_500"' in body
+ assert len(authorization_checks) == 3
def test_show_events_stream_forwards_live_dispatch_events(monkeypatch, tmp_path):
@@ -5860,15 +5884,15 @@ def test_private_show_page_hmr_websocket_requires_remote_session(monkeypatch, tm
_save_config(tmp_path)
_create_show_page("ses123", "private")
- try:
- with app.test_client().websocket_connect(
- "wss://alex.avibe.bot/show/ses123/__vite_hmr",
- headers={"host": "alex.avibe.bot"},
- subprotocols=["vite-hmr"],
- ):
- raise AssertionError("websocket should not connect")
- except Exception as exc:
- assert getattr(exc, "code", None) == 1008
+ with app.test_client().websocket_connect(
+ "wss://alex.avibe.bot/show/ses123/__vite_hmr",
+ headers={"host": "alex.avibe.bot"},
+ subprotocols=["vite-hmr"],
+ ) as websocket:
+ with pytest.raises(WebSocketDisconnect) as exc:
+ websocket.receive_text()
+
+ assert exc.value.code == ui_server._AUTHORIZATION_LOGIN_REQUIRED_WEBSOCKET_CLOSE_CODE
def test_private_show_page_hmr_websocket_accepts_remote_session(monkeypatch, tmp_path):
@@ -5896,8 +5920,13 @@ def test_private_show_page_hmr_websocket_accepts_remote_session(monkeypatch, tmp
set_show_runtime_manager_for_tests(None)
-def test_private_show_page_hmr_websocket_closes_at_authorization_refresh_deadline(monkeypatch, tmp_path):
+def test_private_show_page_hmr_websocket_closes_when_authorization_is_unavailable(
+ monkeypatch,
+ tmp_path,
+):
class RecordingWebSocket:
+ headers = {"host": "alex.avibe.bot"}
+
def __init__(self):
self.calls = []
@@ -5934,12 +5963,13 @@ def test_private_show_page_hmr_websocket_closes_at_authorization_refresh_deadlin
)
engine.dispose()
monkeypatch.setattr(ui_server, "_show_runtime_hmr_origin_allowed", lambda websocket: True)
+ monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)
monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda websocket, **kwargs: True)
monkeypatch.setattr(ui_server, "_project_session_access_allowed", lambda *args: True)
monkeypatch.setattr(
ui_server,
"_show_runtime_websocket_resource_context",
- lambda websocket: resource_access_service.ResourceUserContext(
+ lambda websocket, **kwargs: resource_access_service.ResourceUserContext(
instance_role="viewer",
subject="remote-member",
instance_access_source="organization_group",
@@ -5949,24 +5979,29 @@ def test_private_show_page_hmr_websocket_closes_at_authorization_refresh_deadlin
is_remote=True,
),
)
+ remote_payload = {
+ "sub": "remote-member",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "membership-1",
+ "vibe_organization_role": "member",
+ }
+
+ async def authorize(*args, **kwargs):
+ return {"sub": "remote-member"}, remote_access.AuthorizationResolution(
+ "current",
+ payload=remote_payload,
+ )
+
+ async def authorization_loss(*args, **kwargs):
+ return "unavailable"
+
+ monkeypatch.setattr(ui_server, "_remote_access_websocket_authorization", authorize)
monkeypatch.setattr(
ui_server,
- "_remote_access_websocket_session_claims",
- lambda websocket, config: {
- "sub": "remote-member",
- "vibe_instance_role": "viewer",
- "vibe_instance_access_source": "organization_group",
- "vibe_organization_id": "org-1",
- "vibe_organization_member_id": "membership-1",
- "vibe_organization_role": "member",
- "claims_issued_at": 1,
- },
- )
- monkeypatch.setattr(remote_access, "session_authorization_is_current", lambda *args: True)
- monkeypatch.setattr(
- remote_access,
- "session_authorization_refresh_deadline",
- lambda payload: ui_server.time.time() + 0.01,
+ "_wait_for_remote_session_authorization_loss",
+ authorization_loss,
)
monkeypatch.setattr(ui_server, "_proxy_show_runtime_websocket", blocking_proxy)
websocket = RecordingWebSocket()
@@ -5975,7 +6010,7 @@ def test_private_show_page_hmr_websocket_closes_at_authorization_refresh_deadlin
assert websocket.calls == [
("accept", "vite-hmr"),
- ("close", ui_server._AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE),
+ ("close", ui_server._AUTHORIZATION_UNAVAILABLE_WEBSOCKET_CLOSE_CODE),
]
assert proxy_calls == [("started", "ses123"), ("cancelled", "ses123")]
@@ -5988,6 +6023,8 @@ def test_remote_org_show_page_hmr_closes_when_resource_access_is_revoked(
from vibe.sse_broker import broker
class RecordingWebSocket:
+ headers = {"host": "alex.avibe.bot"}
+
def __init__(self):
self.calls = []
@@ -6025,25 +6062,38 @@ def test_remote_org_show_page_hmr_closes_when_resource_access_is_revoked(
)
engine.dispose()
monkeypatch.setattr(ui_server, "_show_runtime_hmr_origin_allowed", lambda websocket: True)
+ monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)
monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda websocket, **kwargs: True)
+ remote_payload = {
+ "sub": "remote-editor",
+ "email": "[email protected]",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "member-remote-editor",
+ "vibe_organization_role": "member",
+ "vibe_group_ids": ["group-engineering"],
+ }
+
+ async def authorize(*args, **kwargs):
+ return {"sub": "remote-editor"}, remote_access.AuthorizationResolution(
+ "current",
+ payload=remote_payload,
+ )
+
+ async def authorization_loss(*args, **kwargs):
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(ui_server, "_remote_access_websocket_authorization", authorize)
monkeypatch.setattr(
ui_server,
- "_remote_access_websocket_session_claims",
- lambda websocket, config: {
- "sub": "remote-editor",
- "email": "[email protected]",
- "vibe_instance_role": "editor",
- "vibe_instance_access_source": "organization_group",
- "vibe_organization_id": "org-1",
- "vibe_organization_member_id": "member-remote-editor",
- "vibe_organization_role": "member",
- "vibe_group_ids": ["group-engineering"],
- },
+ "_wait_for_remote_session_authorization_loss",
+ authorization_loss,
)
monkeypatch.setattr(
ui_server,
"_show_runtime_websocket_resource_context",
- lambda websocket: resource_access_service.ResourceUserContext(
+ lambda websocket, **kwargs: resource_access_service.ResourceUserContext(
subject="remote-editor",
organization_id="org-1",
@@ -6084,7 +6134,7 @@ def test_remote_org_show_page_hmr_closes_when_resource_access_is_revoked(
assert websocket.calls == [
("accept", "vite-hmr"),
- ("close", ui_server._AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE),
+ ("close", ui_server._AUTHORIZATION_REVOKED_WEBSOCKET_CLOSE_CODE),
]
assert proxy_calls == [("started", "ses123"), ("cancelled", "ses123")]
diff --git a/ui/src/App.remoteAuth.test.tsx b/ui/src/App.remoteAuth.test.tsx
new file mode 100644
index 000000000..21a58b15d
--- /dev/null
+++ b/ui/src/App.remoteAuth.test.tsx
@@ -0,0 +1,128 @@
+/* @vitest-environment jsdom */
+
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { MemoryRouter } from 'react-router-dom';
+
+import { AuthGuard } from './App';
+import { DENIED_INSTANCE_CAPABILITIES } from './lib/sessionInfo';
+import { reportRemoteAuthorizationState, REMOTE_AUTH_STATE_EVENT } from './lib/remoteAuth';
+
+vi.hoisted(() => {
+ vi.stubGlobal('matchMedia', vi.fn().mockImplementation((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })));
+});
+
+const api = vi.hoisted(() => ({
+ getAuthSession: vi.fn(),
+ getConfig: vi.fn(),
+}));
+
+vi.mock('./context/ApiContext', () => ({
+ useApi: () => api,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+afterEach(() => {
+ reportRemoteAuthorizationState('current');
+ cleanup();
+ vi.clearAllMocks();
+ vi.useRealTimers();
+});
+
+describe('AuthGuard remote authorization recovery', () => {
+ it('refreshes the session when an in-shell outage recovers in the same tick', async () => {
+ const session = {
+ remote: true as const,
+ authenticated: true as const,
+ email: '[email protected]',
+ instance_kind: 'organization' as const,
+ instance_role: 'viewer' as const,
+ capabilities: {
+ ...DENIED_INSTANCE_CAPABILITIES,
+ can_read_instance: true,
+ },
+ authorization_state: 'current' as const,
+ };
+ api.getAuthSession.mockResolvedValue(session);
+
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <AuthGuard><div>protected shell</div></AuthGuard>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByText('protected shell')).toBeTruthy();
+ expect(api.getAuthSession).toHaveBeenCalledOnce();
+
+ act(() => {
+ window.dispatchEvent(new CustomEvent(REMOTE_AUTH_STATE_EVENT, {
+ detail: { state: 'unavailable' },
+ }));
+ window.dispatchEvent(new CustomEvent(REMOTE_AUTH_STATE_EVENT, {
+ detail: { state: 'current' },
+ }));
+ });
+
+ await waitFor(() => expect(api.getAuthSession).toHaveBeenCalledTimes(2));
+ expect(await screen.findByText('protected shell')).toBeTruthy();
+ });
+
+ it('automatically probes again after an unavailable cold load', async () => {
+ vi.useFakeTimers();
+ api.getAuthSession
+ .mockResolvedValueOnce({
+ remote: true,
+ authenticated: true,
+ email: '[email protected]',
+ instance_kind: 'organization',
+ authorization_state: 'unavailable',
+ })
+ .mockResolvedValue({
+ remote: true,
+ authenticated: true,
+ email: '[email protected]',
+ instance_kind: 'organization',
+ instance_role: 'viewer',
+ capabilities: {
+ ...DENIED_INSTANCE_CAPABILITIES,
+ can_read_instance: true,
+ },
+ authorization_state: 'current',
+ });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: async () => ({
+ remote: true,
+ authenticated: true,
+ authorization_state: 'current',
+ }),
+ }));
+
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <AuthGuard><div>protected shell</div></AuthGuard>
+ </MemoryRouter>,
+ );
+ await act(async () => undefined);
+ expect(screen.getByText('remoteAuthorization.unavailable.body')).toBeTruthy();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_000);
+ });
+ await act(async () => undefined);
+
+ expect(api.getAuthSession).toHaveBeenCalledTimes(2);
+ expect(screen.getByText('protected shell')).toBeTruthy();
+ });
+});
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index c85f0ea23..629e0d405 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -56,6 +56,9 @@ import {
isSetupCheckBypassed,
remoteLoginPath,
REMOTE_AUTH_REQUIRED_EVENT,
+ REMOTE_AUTH_STATE_EVENT,
+ reportRemoteAuthorizationState,
+ type RemoteAuthorizationState,
shouldBypassSetupForRemoteOwner,
shouldDeferRemoteAuthRedirect,
} from './lib/remoteAuth';
@@ -144,6 +147,31 @@ const RemoteLoginGate = ({ target }: { target: string }) => {
return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;
};
+const RemoteAuthorizationGate = ({
+ state,
+ onRetry,
+}: {
+ state: 'revoked' | 'unavailable';
+ onRetry: () => void;
+}) => {
+ const { t } = useTranslation();
+ return (
+ <main className="min-h-screen flex items-center justify-center bg-bg text-text p-4">
+ <Card className="max-w-md w-full">
+ <CardHeader>
+ <CardTitle>{t(`remoteAuthorization.${state}.title`)}</CardTitle>
+ <CardDescription>{t(`remoteAuthorization.${state}.body`)}</CardDescription>
+ </CardHeader>
+ {state === 'unavailable' ? (
+ <CardContent>
+ <Button onClick={onRetry}>{t('remoteAuthorization.retry')}</Button>
+ </CardContent>
+ ) : null}
+ </Card>
+ </main>
+ );
+};
+
// Server error codes (from the Web UI's enforce_remote_access_cookie guard)
// that mean the control UI is reachable but is refusing THIS request on
// policy grounds — a disallowed entry host, or broken remote-access config —
@@ -203,7 +231,14 @@ const AccessBlocked = ({ code }: { code: string | null }) => {
);
};
-type GuardStatus = 'loading' | 'ready' | 'needs-setup' | 'remote-login-required' | 'access-blocked';
+type GuardStatus =
+ | 'loading'
+ | 'ready'
+ | 'needs-setup'
+ | 'remote-login-required'
+ | 'authorization-revoked'
+ | 'authorization-unavailable'
+ | 'access-blocked';
const notificationClickPath = (value: unknown): string | null => {
if (typeof value !== 'string' || !value.startsWith('/')) return null;
@@ -244,7 +279,7 @@ const WebPushNotificationNavigator = () => {
// change and reset the layout to a "Loading..." div while the two API
// calls round-tripped — that made every sidebar click feel like a full
// page reload because ``<AppShell>`` got unmounted and re-mounted.
-const AuthGuard = ({ children }: { children: ReactNode }) => {
+export const AuthGuard = ({ children }: { children: ReactNode }) => {
const { getConfig, getAuthSession } = useApi();
const { t } = useTranslation();
const location = useLocation();
@@ -253,6 +288,8 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
const [blockedCode, setBlockedCode] = useState<string | null>(null);
const [authCheckVersion, setAuthCheckVersion] = useState(0);
const [authorizationSession, setAuthorizationSession] = useState<SessionInfo | null>(null);
+ const [authorizationUnavailable, setAuthorizationUnavailable] = useState(false);
+ const authorizationUnavailableRef = useRef(false);
const bypassSetupGuard = isSetupCheckBypassed(location.pathname);
// Re-validate only when crossing the setup boundary, not on every
// route change. The wizard completes by saving config and navigating
@@ -268,9 +305,41 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
useEffect(() => {
const onRemoteAuthRequired = () => setGuardStatus('remote-login-required');
+ const onRemoteAuthorizationState = (event: Event) => {
+ const state = (event as CustomEvent<{ state?: RemoteAuthorizationState }>).detail?.state;
+ if (state === 'revoked') {
+ authorizationUnavailableRef.current = false;
+ setAuthorizationUnavailable(false);
+ setGuardStatus('authorization-revoked');
+ } else if (state === 'unavailable') {
+ if (guardStatus === 'ready') {
+ authorizationUnavailableRef.current = true;
+ setAuthorizationUnavailable(true);
+ } else {
+ authorizationUnavailableRef.current = false;
+ setGuardStatus('authorization-unavailable');
+ }
+ } else if (state === 'current') {
+ const recoveredFromUnavailable = authorizationUnavailableRef.current
+ || guardStatus === 'authorization-unavailable';
+ authorizationUnavailableRef.current = false;
+ setAuthorizationUnavailable(false);
+ if (recoveredFromUnavailable) {
+ setAuthCheckVersion((version) => version + 1);
+ }
+ } else if (state === 'changed') {
+ authorizationUnavailableRef.current = false;
+ setAuthorizationUnavailable(false);
+ setAuthCheckVersion((version) => version + 1);
+ }
+ };
window.addEventListener(REMOTE_AUTH_REQUIRED_EVENT, onRemoteAuthRequired);
- return () => window.removeEventListener(REMOTE_AUTH_REQUIRED_EVENT, onRemoteAuthRequired);
- }, []);
+ window.addEventListener(REMOTE_AUTH_STATE_EVENT, onRemoteAuthorizationState);
+ return () => {
+ window.removeEventListener(REMOTE_AUTH_REQUIRED_EVENT, onRemoteAuthRequired);
+ window.removeEventListener(REMOTE_AUTH_STATE_EVENT, onRemoteAuthorizationState);
+ };
+ }, [guardStatus]);
useEffect(() => {
if (guardStatus !== 'remote-login-required' || !shouldDeferRemoteAuthRedirect()) return;
@@ -306,7 +375,29 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
setGuardStatus('remote-login-required');
return null;
}
- if (session.remote && session.authenticated && !session.capabilities.can_manage_instance) {
+ if (
+ session.remote
+ && session.authenticated
+ && session.authorization_state === 'revoked'
+ ) {
+ setGuardStatus('authorization-revoked');
+ return null;
+ }
+ if (
+ session.remote
+ && session.authenticated
+ && session.authorization_state === 'unavailable'
+ ) {
+ setGuardStatus('authorization-unavailable');
+ reportRemoteAuthorizationState('unavailable');
+ return null;
+ }
+ if (
+ session.remote
+ && session.authenticated
+ && session.authorization_state === 'current'
+ && !session.capabilities.can_manage_instance
+ ) {
setGuardStatus('ready');
return null;
}
@@ -339,6 +430,23 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
setGuardStatus('remote-login-required');
return;
}
+ if (
+ authCheck?.session.remote
+ && authCheck.session.authenticated
+ && authCheck.session.authorization_state === 'revoked'
+ ) {
+ setGuardStatus('authorization-revoked');
+ return;
+ }
+ if (
+ authCheck?.session.remote
+ && authCheck.session.authenticated
+ && authCheck.session.authorization_state === 'unavailable'
+ ) {
+ setGuardStatus('authorization-unavailable');
+ reportRemoteAuthorizationState('unavailable');
+ return;
+ }
if (authCheck && !authCheck.checkSetup) {
setGuardStatus('ready');
return;
@@ -376,6 +484,22 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
if (guardStatus === 'remote-login-required') {
return <RemoteLoginGate target={guardTarget} />;
}
+ if (guardStatus === 'authorization-revoked') {
+ return (
+ <RemoteAuthorizationGate
+ state="revoked"
+ onRetry={() => undefined}
+ />
+ );
+ }
+ if (guardStatus === 'authorization-unavailable') {
+ return (
+ <RemoteAuthorizationGate
+ state="unavailable"
+ onRetry={() => reportRemoteAuthorizationState('changed')}
+ />
+ );
+ }
if (guardStatus === 'access-blocked') {
return <AccessBlocked code={blockedCode} />;
}
@@ -403,7 +527,26 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
if (!authorizationSession) {
return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;
}
- return <InstanceAuthorizationProvider session={authorizationSession}>{children}</InstanceAuthorizationProvider>;
+ return (
+ <>
+ <InstanceAuthorizationProvider session={authorizationSession}>{children}</InstanceAuthorizationProvider>
+ {authorizationUnavailable ? (
+ <div
+ role="status"
+ className="fixed inset-x-3 bottom-3 z-[100] mx-auto flex max-w-xl items-center justify-between gap-3 border border-border bg-surface px-3 py-2 text-sm text-text shadow-lg"
+ >
+ <span>{t('remoteAuthorization.unavailable.body')}</span>
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => reportRemoteAuthorizationState('changed')}
+ >
+ {t('remoteAuthorization.retry')}
+ </Button>
+ </div>
+ ) : null}
+ </>
+ );
};
// Brief fallback while a lazy Apps route chunk loads (the pages render their own
diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsx
index 2f89a1f90..90ae9ee92 100644
--- a/ui/src/components/workbench/TerminalView.tsx
+++ b/ui/src/components/workbench/TerminalView.tsx
@@ -18,6 +18,11 @@ import {
import { IS_APPLE } from '../../lib/platform';
import { openLinkInNewContext } from '../../lib/pwaNavigation';
import { useLatestRef } from '@/lib/useLatestRef';
+import {
+ REMOTE_AUTH_STATE_EVENT,
+ reportRemoteAuthorizationState,
+ type RemoteAuthorizationState,
+} from '@/lib/remoteAuth';
// xterm.js wired to the /api/terminal/{id} WebSocket. Protocol (locked with the
// backend): client sends raw stdin as BINARY frames and JSON control as TEXT
@@ -28,7 +33,10 @@ export type TerminalStatus = 'connecting' | 'ready' | 'closed' | 'disabled' | 'e
const ENC = new TextEncoder();
const MAX_BUSY_RETRIES = 3; // auto-retry a transient "busy" (1013) close this many times
-const AUTHORIZATION_REFRESH_CLOSE_CODE = 4401;
+const AUTHORIZATION_LOGIN_REQUIRED_CLOSE_CODE = 4401;
+const AUTHORIZATION_REVOKED_CLOSE_CODE = 4403;
+const AUTHORIZATION_UNAVAILABLE_CLOSE_CODE = 4503;
+const AUTHORIZATION_CHANGED_CLOSE_CODE = 1012;
// The terminal window is theme-locked to dark (registry lockTheme: a shell is conventionally
// dark, like a code editor), so xterm carries a fixed dark palette regardless of the global theme.
@@ -143,6 +151,7 @@ export const TerminalView: React.FC<{
const ctrlStickyRef = useRef(false);
const busyRetriesRef = useRef(0);
const retryTimerRef = useRef<number | null>(null);
+ const authorizationRecoveryPendingRef = useRef(false);
// Auto-dismiss timer for the mobile Paste key's "clipboard blocked" hint.
const pasteHintTimerRef = useRef<number | null>(null);
// Report actual session persistence (from the backend 'ready' frame) up to the tab bar, so its
@@ -168,6 +177,17 @@ export const TerminalView: React.FC<{
onStatusRef.current?.(status, exitCode);
}, [status, exitCode]);
+ useEffect(() => {
+ const onAuthorizationState = (event: Event) => {
+ const state = (event as CustomEvent<{ state?: RemoteAuthorizationState }>).detail?.state;
+ if (state !== 'current' || !authorizationRecoveryPendingRef.current) return;
+ authorizationRecoveryPendingRef.current = false;
+ setReconnectKey((key) => key + 1);
+ };
+ window.addEventListener(REMOTE_AUTH_STATE_EVENT, onAuthorizationState);
+ return () => window.removeEventListener(REMOTE_AUTH_STATE_EVENT, onAuthorizationState);
+ }, []);
+
useEffect(() => {
const term = new Terminal({
fontSize: getTerminalFontSize(), // shared, persisted preference — see terminalFontSize.ts
@@ -333,8 +353,31 @@ export const TerminalView: React.FC<{
term.write(new Uint8Array(ev.data as ArrayBuffer));
};
ws.onclose = (ev: CloseEvent) => {
- if (ev.code === AUTHORIZATION_REFRESH_CLOSE_CODE) {
- window.location.reload();
+ if (ev.code === AUTHORIZATION_LOGIN_REQUIRED_CLOSE_CODE) {
+ authorizationRecoveryPendingRef.current = true;
+ setStatus('error');
+ reportRemoteAuthorizationState('login_required');
+ return;
+ }
+ if (ev.code === AUTHORIZATION_REVOKED_CLOSE_CODE) {
+ authorizationRecoveryPendingRef.current = false;
+ setStatus('disabled');
+ reportRemoteAuthorizationState('revoked');
+ return;
+ }
+ if (ev.code === AUTHORIZATION_UNAVAILABLE_CLOSE_CODE) {
+ authorizationRecoveryPendingRef.current = true;
+ setStatus('error');
+ reportRemoteAuthorizationState('unavailable');
+ return;
+ }
+ if (ev.code === AUTHORIZATION_CHANGED_CLOSE_CODE) {
+ setStatus('connecting');
+ reportRemoteAuthorizationState('changed');
+ retryTimerRef.current = window.setTimeout(
+ () => setReconnectKey((key) => key + 1),
+ 250,
+ );
return;
}
// 1013 = transient "try again shortly" (the session id is mid-open/teardown, or the cap
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 76c267b92..8eb7bcce1 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -31,6 +31,8 @@ import {
type SessionDraftServerState,
type SessionDraftWrite,
} from '../lib/sessionDraftPersistence';
+import { getExistingWebPushSubscription, getWebPushDeviceId } from '../lib/webPush';
+import { reportRemoteAuthorizationState, type RemoteAuthorizationState } from '../lib/remoteAuth';
export type { InstanceCapabilities, SessionInfo };
export type { ShowPageAccess };
@@ -2845,6 +2847,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
handlers.onAuthorizationChanged?.(envelope.data);
});
});
+ source.addEventListener('remote.authorization', (e: MessageEvent) => {
+ try {
+ const payload = JSON.parse(e.data) as { state?: RemoteAuthorizationState };
+ if (payload.state) reportRemoteAuthorizationState(payload.state);
+ } catch (err) {
+ console.error('[workbench-events] remote authorization parse failed', err, e.data);
+ }
+ });
source.addEventListener('message.new', (e: MessageEvent) => {
const envelope = parseWorkbenchEnvelope<WorkbenchMessage>(e.data);
if (!envelope) return;
@@ -4039,7 +4049,18 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
saveRemoteAccessSettings: (settings) => postJson('/api/remote-access/settings', settings),
diagnoseRemoteAccess: () => postJson('/api/remote-access/diagnostics', {}),
getAuthSession: () => getJson('/api/session').then(normalizeSessionInfo),
- signOut: () => postJson('/auth/logout', {}),
+ signOut: async () => {
+ let endpoint: string | undefined;
+ try {
+ endpoint = (await getExistingWebPushSubscription())?.endpoint;
+ } catch {
+ // Logout remains authoritative when Push APIs are unavailable.
+ }
+ return postJson('/auth/logout', {
+ device_id: getWebPushDeviceId(),
+ ...(endpoint ? { endpoint } : {}),
+ });
+ },
// eslint-disable-next-line react-hooks/exhaustive-deps
}), [sessionDraftPersistence, showToast, t]);
diff --git a/ui/src/context/InstanceAuthorizationProvider.tsx b/ui/src/context/InstanceAuthorizationProvider.tsx
index 3492a0403..6b49f1169 100644
--- a/ui/src/context/InstanceAuthorizationProvider.tsx
+++ b/ui/src/context/InstanceAuthorizationProvider.tsx
@@ -26,7 +26,7 @@ export const InstanceAuthorizationProvider = ({
capabilities: session.capabilities ?? OWNER_INSTANCE_CAPABILITIES,
};
}
- if (!session.authenticated) {
+ if (!session.authenticated || session.authorization_state !== 'current') {
return {
remote: true,
instanceKind: null,
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index eef658b5c..4b04ab976 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -18,6 +18,17 @@
"body": "Sign in with Avibe Cloud to continue securely.",
"action": "Sign in"
},
+ "remoteAuthorization": {
+ "revoked": {
+ "title": "Access removed",
+ "body": "Your access to this Avibe instance has been removed."
+ },
+ "unavailable": {
+ "title": "Access check unavailable",
+ "body": "Avibe cannot verify access right now. It will reconnect automatically."
+ },
+ "retry": "Retry now"
+ },
"preview": {
"title": "Preview",
"unsupported": "This file can't be previewed.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 2755ce53e..e59fe7890 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -18,6 +18,17 @@
"body": "使用 Avibe Cloud 登录后即可安全地继续访问。",
"action": "重新登录"
},
+ "remoteAuthorization": {
+ "revoked": {
+ "title": "访问权限已移除",
+ "body": "你已无法访问这个 Avibe 实例。"
+ },
+ "unavailable": {
+ "title": "暂时无法验证访问权限",
+ "body": "Avibe 目前无法验证访问权限,将自动重连。"
+ },
+ "retry": "立即重试"
+ },
"preview": {
"title": "预览",
"unsupported": "此文件无法预览。",
diff --git a/ui/src/lib/apiFetch.test.ts b/ui/src/lib/apiFetch.test.ts
index 1bc8f31df..e24926158 100644
--- a/ui/src/lib/apiFetch.test.ts
+++ b/ui/src/lib/apiFetch.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const remoteAuth = vi.hoisted(() => ({
deferRemoteAuthRedirect: vi.fn(),
+ reportRemoteAuthorizationState: vi.fn(),
remoteLoginPath: vi.fn((target: string) => `/auth/login?next=${encodeURIComponent(target)}`),
}));
@@ -42,7 +43,9 @@ describe('apiFetch remote auth recovery', () => {
const response = await apiFetch('/api/inbox');
expect(response.status).toBe(401);
- await vi.waitFor(() => expect(remoteAuth.deferRemoteAuthRedirect).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(remoteAuth.reportRemoteAuthorizationState).toHaveBeenCalledWith(
+ 'login_required',
+ ));
expect(window.location.assign).not.toHaveBeenCalled();
},
);
@@ -56,7 +59,7 @@ describe('apiFetch remote auth recovery', () => {
await apiFetch('/api/inbox');
await new Promise((resolve) => setTimeout(resolve, 0));
- expect(remoteAuth.deferRemoteAuthRedirect).not.toHaveBeenCalled();
+ expect(remoteAuth.reportRemoteAuthorizationState).not.toHaveBeenCalled();
});
it('replays a rejected mutation with the cookie that replaced its header token', async () => {
@@ -386,12 +389,11 @@ describe('apiFetch remote auth recovery', () => {
authorization_refresh_required: true,
}));
- expect(remoteAuth.deferRemoteAuthRedirect).toHaveBeenCalledOnce();
+ expect(remoteAuth.reportRemoteAuthorizationState).toHaveBeenCalledWith('login_required');
expect(window.location.assign).not.toHaveBeenCalled();
});
- it('uses the dedicated login endpoint outside an iOS standalone PWA', async () => {
- remoteAuth.deferRemoteAuthRedirect.mockReturnValue(false);
+ it('reports login-required responses to the shared recovery owner', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () =>
@@ -401,10 +403,9 @@ describe('apiFetch remote auth recovery', () => {
await apiFetch('/api/inbox');
- await vi.waitFor(() => expect(window.location.assign).toHaveBeenCalledWith(
- '/auth/login?next=%2Finbox%3Ffilter%3Dopen',
+ await vi.waitFor(() => expect(remoteAuth.reportRemoteAuthorizationState).toHaveBeenCalledWith(
+ 'login_required',
));
- expect(remoteAuth.remoteLoginPath).toHaveBeenCalledWith('/inbox?filter=open');
});
it('evicts a stalled shared CSRF refresh after a rejected mutation aborts', async () => {
diff --git a/ui/src/lib/apiFetch.ts b/ui/src/lib/apiFetch.ts
index 4c3a17e97..d05006b9b 100644
--- a/ui/src/lib/apiFetch.ts
+++ b/ui/src/lib/apiFetch.ts
@@ -1,4 +1,4 @@
-import { deferRemoteAuthRedirect, remoteLoginPath } from './remoteAuth';
+import { reportRemoteAuthorizationState } from './remoteAuth';
const CSRF_COOKIE_NAME = 'vibe_csrf_token';
const CSRF_HEADER_NAME = 'X-Vibe-CSRF-Token';
@@ -7,6 +7,8 @@ const REMOTE_AUTH_RECOVERY_ERRORS = new Set([
'remote_access_login_required',
'remote_access_authorization_refresh_required',
]);
+const REMOTE_AUTH_REVOKED_ERROR = 'remote_access_revoked';
+const REMOTE_AUTH_UNAVAILABLE_ERROR = 'remote_access_authorization_unavailable';
let csrfTokenPromise: Promise<string> | null = null;
// Preserve owned-deadline identity across the operation boundary without
@@ -265,18 +267,14 @@ export async function apiFetch(
// answering /api/* with a remote login/authorization-refresh 401. Detect it
// here and trigger the same full-page login redirect the guard uses, so the
// user lands on the login flow instead of a wall of silently-failing fetches.
- if (response.status === 401) {
- void maybeRedirectOnRemoteAuthExpiry(response.clone());
+ if (response.status === 401 || response.status === 403 || response.status === 503) {
+ void maybeReportRemoteAuthorizationResponse(response.clone());
}
return response;
}
-let redirectingForRemoteAuth = false;
-
-async function maybeRedirectOnRemoteAuthExpiry(response: Response): Promise<void> {
- if (redirectingForRemoteAuth || typeof window === 'undefined') {
- return;
- }
+async function maybeReportRemoteAuthorizationResponse(response: Response): Promise<void> {
+ if (typeof window === 'undefined') return;
let payload: unknown;
try {
payload = await response.json();
@@ -285,10 +283,14 @@ async function maybeRedirectOnRemoteAuthExpiry(response: Response): Promise<void
return;
}
const error = (payload as { error?: string } | null)?.error;
- if (!error || !REMOTE_AUTH_RECOVERY_ERRORS.has(error)) {
- return;
+ if (!error) return;
+ if (REMOTE_AUTH_RECOVERY_ERRORS.has(error)) {
+ reportRemoteAuthorizationState('login_required');
+ } else if (error === REMOTE_AUTH_REVOKED_ERROR) {
+ reportRemoteAuthorizationState('revoked');
+ } else if (error === REMOTE_AUTH_UNAVAILABLE_ERROR) {
+ reportRemoteAuthorizationState('unavailable');
}
- beginRemoteAuthRecovery();
}
export async function recoverRemoteAuthFromSessionProbe(response: Response): Promise<void> {
@@ -303,26 +305,25 @@ export async function recoverRemoteAuthFromSessionProbe(response: Response): Pro
remote?: boolean;
authenticated?: boolean;
authorization_refresh_required?: boolean;
+ authorization_state?: 'current' | 'revoked' | 'unavailable';
} | null;
+ if (session?.authorization_state === 'revoked') {
+ reportRemoteAuthorizationState('revoked');
+ return;
+ }
+ if (session?.authorization_state === 'unavailable') {
+ reportRemoteAuthorizationState('unavailable');
+ return;
+ }
+ if (session?.authorization_state === 'current') {
+ reportRemoteAuthorizationState('current');
+ return;
+ }
if (
session?.remote === true
&& session.authenticated === false
&& session.authorization_refresh_required === true
) {
- beginRemoteAuthRecovery();
+ reportRemoteAuthorizationState('login_required');
}
}
-
-function beginRemoteAuthRecovery(): void {
- if (redirectingForRemoteAuth || typeof window === 'undefined') {
- return;
- }
- // A cross-origin OAuth redirect from an iOS Home-Screen app opens in a
- // separate browser sheet. Never raise that sheet automatically: hand control
- // back to AuthGuard so the PWA can ask for an explicit sign-in action.
- if (deferRemoteAuthRedirect()) return;
-
- redirectingForRemoteAuth = true;
- const target = window.location.pathname + window.location.search;
- window.location.assign(remoteLoginPath(target));
-}
diff --git a/ui/src/lib/remoteAuth.test.ts b/ui/src/lib/remoteAuth.test.ts
index 479780131..2f5c86fb5 100644
--- a/ui/src/lib/remoteAuth.test.ts
+++ b/ui/src/lib/remoteAuth.test.ts
@@ -10,9 +10,11 @@ vi.mock('./platform', () => platform);
import {
checkRemoteAuthForPath,
deferRemoteAuthRedirect,
+ reportRemoteAuthorizationState,
remoteLoginPath,
shouldBypassSetupForRemoteOwner,
REMOTE_AUTH_REQUIRED_EVENT,
+ REMOTE_AUTH_STATE_EVENT,
shouldDeferRemoteAuthRedirect,
} from './remoteAuth';
@@ -90,6 +92,79 @@ describe('remote auth navigation', () => {
});
});
+describe('remote authorization recovery', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ reportRemoteAuthorizationState('current');
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it('keeps probing with bounded backoff until authorization recovers', async () => {
+ const dispatchEvent = vi.fn();
+ vi.stubGlobal('window', {
+ clearTimeout: globalThis.clearTimeout,
+ dispatchEvent,
+ setTimeout: globalThis.setTimeout,
+ });
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce({
+ json: async () => ({
+ remote: true,
+ authenticated: true,
+ authorization_state: 'unavailable',
+ }),
+ })
+ .mockResolvedValueOnce({
+ json: async () => ({
+ remote: true,
+ authenticated: true,
+ authorization_state: 'current',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ reportRemoteAuthorizationState('unavailable');
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1_999);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(dispatchEvent.mock.calls.some(([event]) => (
+ event.type === REMOTE_AUTH_STATE_EVENT && event.detail?.state === 'current'
+ ))).toBe(true);
+ });
+
+ it('replaces a pending backoff with an immediate manual retry', async () => {
+ const dispatchEvent = vi.fn();
+ vi.stubGlobal('window', {
+ clearTimeout: globalThis.clearTimeout,
+ dispatchEvent,
+ setTimeout: globalThis.setTimeout,
+ });
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: async () => ({
+ remote: true,
+ authenticated: true,
+ authorization_state: 'current',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ reportRemoteAuthorizationState('unavailable');
+ reportRemoteAuthorizationState('changed');
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+});
+
describe('setup bypass for remote runtime access', () => {
it('bypasses setup only for an authenticated Instance Owner', () => {
expect(
diff --git a/ui/src/lib/remoteAuth.ts b/ui/src/lib/remoteAuth.ts
index 52b7ff69c..c85768721 100644
--- a/ui/src/lib/remoteAuth.ts
+++ b/ui/src/lib/remoteAuth.ts
@@ -1,6 +1,7 @@
import { isIosDevice, isStandalonePwa } from './platform';
export const REMOTE_AUTH_REQUIRED_EVENT = 'avibe.remote-auth-required';
+export const REMOTE_AUTH_STATE_EVENT = 'avibe.remote-auth-state';
const REMOTE_LOGIN_PATH = '/auth/login';
const SETUP_CHECK_BYPASS_PATHS = new Set(['/admin/logs', '/admin/settings/diagnostics']);
@@ -11,7 +12,24 @@ type PwaContext = {
type RemoteSession =
| { remote: false }
- | { remote: true; authenticated: boolean };
+ | {
+ remote: true;
+ authenticated: boolean;
+ authorization_state?: 'current' | 'revoked' | 'unavailable';
+ };
+
+export type RemoteAuthorizationState =
+ | 'current'
+ | 'changed'
+ | 'login_required'
+ | 'revoked'
+ | 'unavailable';
+
+const AUTHORIZATION_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000] as const;
+let authorizationRetryIndex = 0;
+let authorizationRetryTimer: number | null = null;
+let authorizationProbeRunning = false;
+let redirectingForRemoteAuth = false;
export function shouldDeferRemoteAuthRedirect(
context: PwaContext = { ios: isIosDevice(), standalone: isStandalonePwa() },
@@ -60,3 +78,97 @@ export function deferRemoteAuthRedirect(): boolean {
window.dispatchEvent(new Event(REMOTE_AUTH_REQUIRED_EVENT));
return true;
}
+
+function dispatchRemoteAuthorizationState(state: RemoteAuthorizationState): void {
+ if (typeof window === 'undefined') return;
+ window.dispatchEvent(new CustomEvent(REMOTE_AUTH_STATE_EVENT, { detail: { state } }));
+}
+
+function clearAuthorizationRetry(): void {
+ if (authorizationRetryTimer !== null && typeof window !== 'undefined') {
+ window.clearTimeout(authorizationRetryTimer);
+ }
+ authorizationRetryTimer = null;
+ authorizationRetryIndex = 0;
+}
+
+function scheduleAuthorizationProbe(immediate = false): void {
+ if (typeof window === 'undefined' || authorizationProbeRunning) return;
+ if (authorizationRetryTimer !== null) {
+ if (!immediate) return;
+ window.clearTimeout(authorizationRetryTimer);
+ authorizationRetryTimer = null;
+ }
+ const delay = immediate
+ ? 0
+ : AUTHORIZATION_RETRY_DELAYS_MS[
+ Math.min(authorizationRetryIndex, AUTHORIZATION_RETRY_DELAYS_MS.length - 1)
+ ];
+ authorizationRetryIndex += 1;
+ authorizationRetryTimer = window.setTimeout(() => {
+ authorizationRetryTimer = null;
+ void probeRemoteAuthorization();
+ }, delay);
+}
+
+async function probeRemoteAuthorization(): Promise<void> {
+ if (authorizationProbeRunning) return;
+ authorizationProbeRunning = true;
+ let nextState: RemoteAuthorizationState = 'unavailable';
+ try {
+ const response = await fetch('/api/session', {
+ credentials: 'same-origin',
+ headers: { Accept: 'application/json' },
+ });
+ const session = await response.json().catch(() => null) as {
+ remote?: boolean;
+ authenticated?: boolean;
+ authorization_state?: 'current' | 'revoked' | 'unavailable';
+ } | null;
+ if (session?.remote === false || session?.authorization_state === 'current') {
+ nextState = 'current';
+ } else if (session?.authorization_state === 'revoked') {
+ nextState = 'revoked';
+ } else if (session?.remote === true && session.authenticated === false) {
+ nextState = 'login_required';
+ }
+ } catch {
+ // Keep the default unavailable state. Reporting after the running flag is
+ // cleared lets the reporter arm the next bounded retry.
+ } finally {
+ authorizationProbeRunning = false;
+ }
+ reportRemoteAuthorizationState(nextState);
+}
+
+export function reportRemoteAuthorizationState(state: RemoteAuthorizationState): void {
+ if (state === 'login_required') {
+ clearAuthorizationRetry();
+ dispatchRemoteAuthorizationState(state);
+ beginRemoteAuthRecovery();
+ return;
+ }
+ if (state === 'revoked') {
+ clearAuthorizationRetry();
+ dispatchRemoteAuthorizationState(state);
+ return;
+ }
+ if (state === 'current') {
+ clearAuthorizationRetry();
+ dispatchRemoteAuthorizationState(state);
+ return;
+ }
+ dispatchRemoteAuthorizationState(state);
+ scheduleAuthorizationProbe(state === 'changed');
+}
+
+function beginRemoteAuthRecovery(): void {
+ if (redirectingForRemoteAuth || typeof window === 'undefined') return;
+ // iOS Home-Screen OAuth must remain user-initiated or it opens a browser
+ // sheet that strands the PWA. The AuthGuard owns that explicit action.
+ if (deferRemoteAuthRedirect()) return;
+
+ redirectingForRemoteAuth = true;
+ const target = window.location.pathname + window.location.search;
+ window.location.assign(remoteLoginPath(target));
+}
diff --git a/ui/src/lib/sessionInfo.test.ts b/ui/src/lib/sessionInfo.test.ts
index f3b9544a1..5c14850cb 100644
--- a/ui/src/lib/sessionInfo.test.ts
+++ b/ui/src/lib/sessionInfo.test.ts
@@ -36,6 +36,7 @@ describe('normalizeSessionInfo', () => {
instance_kind: null,
instance_role: 'owner',
capabilities: OWNER_INSTANCE_CAPABILITIES,
+ authorization_state: 'current',
});
});
@@ -63,9 +64,31 @@ describe('normalizeSessionInfo', () => {
can_read_instance: true,
can_use_show_pages: true,
},
+ authorization_state: 'current',
});
});
+ it.each(['revoked', 'unavailable'] as const)(
+ 'keeps an authenticated %s session distinct from login expiry',
+ (authorizationState) => {
+ expect(normalizeSessionInfo({
+ remote: true,
+ authenticated: true,
+ email: '[email protected]',
+ sub: 'member-1',
+ instance_kind: 'organization',
+ authorization_state: authorizationState,
+ })).toEqual({
+ remote: true,
+ authenticated: true,
+ email: '[email protected]',
+ sub: 'member-1',
+ instance_kind: 'organization',
+ authorization_state: authorizationState,
+ });
+ },
+ );
+
it('keeps local sessions owner-compatible when an older server omits capabilities', () => {
expect(normalizeSessionInfo({ remote: false })).toEqual({
remote: false,
diff --git a/ui/src/lib/sessionInfo.ts b/ui/src/lib/sessionInfo.ts
index 0c21360d7..2aba431a4 100644
--- a/ui/src/lib/sessionInfo.ts
+++ b/ui/src/lib/sessionInfo.ts
@@ -16,6 +16,7 @@ export type InstanceCapabilities = {
};
export type InstanceKind = 'personal' | 'organization';
+export type RemoteAuthorizationState = 'current' | 'revoked' | 'unavailable';
export type SessionInfo =
| {
@@ -25,6 +26,14 @@ export type SessionInfo =
capabilities?: InstanceCapabilities;
}
| { remote: true; authenticated: false; authorization_refresh_required?: boolean }
+ | {
+ remote: true;
+ authenticated: true;
+ email: string;
+ sub?: string;
+ instance_kind: InstanceKind | null;
+ authorization_state: 'revoked' | 'unavailable';
+ }
| {
remote: true;
authenticated: true;
@@ -33,6 +42,7 @@ export type SessionInfo =
instance_kind: InstanceKind | null;
instance_role: 'owner' | 'editor' | 'viewer';
capabilities: InstanceCapabilities;
+ authorization_state: 'current';
};
export const DENIED_INSTANCE_CAPABILITIES: InstanceCapabilities = {
@@ -92,6 +102,17 @@ export const normalizeSessionInfo = (value: unknown): SessionInfo => {
};
}
+ if (value.authorization_state === 'revoked' || value.authorization_state === 'unavailable') {
+ return {
+ remote: true,
+ authenticated: true,
+ email: typeof value.email === 'string' ? value.email : '',
+ ...(typeof value.sub === 'string' ? { sub: value.sub } : {}),
+ instance_kind: normalizeInstanceKind(value.instance_kind),
+ authorization_state: value.authorization_state,
+ };
+ }
+
const rawCapabilities = isRecord(value.capabilities) ? value.capabilities : null;
// Releases before instance roles treated every authenticated remote user as
// the instance owner and did not return a capabilities object.
@@ -115,5 +136,6 @@ export const normalizeSessionInfo = (value: unknown): SessionInfo => {
instance_kind: normalizeInstanceKind(value.instance_kind),
instance_role: instanceRole,
capabilities,
+ authorization_state: 'current',
};
};
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 1b8763303..d3f73aaf4 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -45,13 +45,22 @@ logger = logging.getLogger(__name__)
CLOUDFLARED_BASE_URL = "https://github.com/cloudflare/cloudflared/releases/latest/download"
SESSION_COOKIE_NAME = "__Host-vibe_remote_session"
-SESSION_TTL_SECONDS = 24 * 60 * 60
-SESSION_AUTHORIZATION_REFRESH_SECONDS = SESSION_TTL_SECONDS // 2
+PERSONAL_SESSION_TTL_SECONDS = 24 * 60 * 60
+PERSONAL_SESSION_RENEW_AFTER_SECONDS = PERSONAL_SESSION_TTL_SECONDS // 2
+ORGANIZATION_SESSION_TTL_SECONDS = 24 * 60 * 60
+ORGANIZATION_AUTHORIZATION_REFRESH_SECONDS = 12 * 60 * 60
+ORGANIZATION_AUTHORIZATION_OUTAGE_GRACE_SECONDS = 6 * 60 * 60
+# Compatibility aliases for released callers and persisted metadata. Policy
+# decisions below use the independently named Personal/Organization values.
+SESSION_TTL_SECONDS = PERSONAL_SESSION_TTL_SECONDS
+SESSION_AUTHORIZATION_REFRESH_SECONDS = ORGANIZATION_AUTHORIZATION_REFRESH_SECONDS
# Keep enough headroom for the cookie name and attributes under the common
# 4096-byte per-cookie browser limit.
SESSION_COOKIE_MAX_VALUE_BYTES = 3800
_SESSION_AUTHORIZATION_REFERENCE_KEY = "authorization_ref"
_SESSION_AUTHORIZATION_REFERENCE_RE = re.compile(r"\A[A-Za-z0-9_-]{24,64}\Z")
+_SESSION_BROWSER_ID_KEY = "browser_session_id"
+_SESSION_BROWSER_ID_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(
@@ -69,11 +78,27 @@ _STATUS_REPORT_ATEXIT_REGISTERED = False
_ACTIVE_HOSTNAMES_LOCK = threading.Lock()
_ACTIVE_HOSTNAMES_CACHE: tuple[Path, str, frozenset[str], float | None] | None = None
_AUTHORIZATION_REVISION_KEY = "vibe_instance_authorization_revision"
+_AUTHORIZATION_CHECKED_REVISION_KEY = "_authorization_checked_revision"
_AUTHORIZATION_REVISION_LOCK = threading.Lock()
_AUTHORIZATION_REVISION_CACHE: tuple[Path, str, int, float] | None = None
_AUTHORIZATION_REVISION_SYNC_LOCK = threading.Lock()
_AUTHORIZATION_REVISION_POLL_LOCK = threading.Lock()
_AUTHORIZATION_REVISION_POLL_STARTED = False
+_AUTHORIZATION_REFRESH_LOCK = threading.Lock()
+_AUTHORIZATION_REFRESH_FAILURES: dict[tuple[str, str, str, str], float] = {}
+_AUTHORIZATION_REFRESH_RESULTS: dict[
+ tuple[str, str, str, str],
+ tuple[float, str, str | None, int | None],
+] = {}
+_AUTHORIZATION_REFRESH_FLIGHTS: dict[
+ tuple[str, str, str, str],
+ tuple[threading.Lock, int],
+] = {}
+_AUTHORIZATION_BACKGROUND_REFRESH_LOCK = threading.Lock()
+_AUTHORIZATION_BACKGROUND_REFRESHES: set[tuple[str, str, str, str]] = set()
+AUTHORIZATION_REFRESH_FAILURE_BACKOFF_SECONDS = 5.0
+_REVOKED_BROWSER_SESSIONS_LOCK = threading.Lock()
+_REVOKED_BROWSER_SESSIONS: dict[str, int] = {}
STATUS_HEARTBEAT_SECONDS = 5 * 60
RESOURCE_ACL_SYNC_INTERVAL_SECONDS = 30
AUTHORIZATION_REVISION_SYNC_INTERVAL_SECONDS = 15
@@ -148,6 +173,19 @@ class BackendRequestError(Exception):
self.payload = payload
+@dataclass(frozen=True)
+class AuthorizationResolution:
+ state: str
+ payload: dict[str, Any] | None = None
+ policy: str | None = None
+ refreshed: bool = False
+ reason: str | None = None
+
+ @property
+ def current(self) -> bool:
+ return self.state == "current" and self.payload is not None
+
+
@dataclass(frozen=True)
class _ValidatedPairingBackend:
base_url: str
@@ -1427,8 +1465,22 @@ def cloud_token_for_request(
if scope != "asr":
return None
config = config or V2Config.load()
- payload = parse_session_cookie(config, cookie_value)
- if payload is None or session_needs_authorization_refresh(payload):
+ identity = parse_session_identity(config, cookie_value)
+ if identity is None:
+ return None
+ resolution = resolve_current_authorization(config, identity)
+ if not resolution.current:
+ return None
+ return cloud_token_for_authorization(config, resolution.payload, scope=scope)
+
+
+def cloud_token_for_authorization(
+ config: V2Config,
+ payload: Mapping[str, Any],
+ *,
+ scope: str = "asr",
+) -> dict[str, Any] | None:
+ if scope != "asr":
return None
from vibe.authorization import context_from_session_payload
@@ -1591,6 +1643,16 @@ def sync_authorization_revision_once(
config,
result.get("authorization_revision"),
)
+ try:
+ from storage import remote_access_authorization_service
+
+ remote_access_authorization_service.mark_matching_revision_checked(
+ instance_id=str(config.remote_access.vibe_cloud.instance_id),
+ authorization_revision=revision,
+ checked_at=int(time.time()),
+ )
+ except Exception:
+ logger.warning("Authorization revision context update failed", exc_info=True)
return {"ok": True, "authorization_revision": revision}
except BackendRequestError as exc:
error = exc.payload.get("error")
@@ -4162,6 +4224,10 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dict
"error": str(origin_update.get("error") or "tunnel_origin_update_failed"),
"pairing": {"ok": False, "origin_service": origin_service},
}
+ try:
+ previous_instance_id = str(V2Config.load().remote_access.vibe_cloud.instance_id or "")
+ except Exception:
+ previous_instance_id = ""
config = api.save_config(
{
"remote_access": {
@@ -4185,6 +4251,13 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dict
}
}
)
+ if previous_instance_id and previous_instance_id != str(result["instance_id"]):
+ try:
+ from storage import remote_access_authorization_service
+
+ remote_access_authorization_service.delete_for_instance(previous_instance_id)
+ except Exception:
+ logger.warning("Old remote authorization cleanup failed after pairing", exc_info=True)
start_result = start(config)
_report_runtime_status_async(config, event="pair", last_error=start_result.get("error"))
return {**status(config), "ok": True, "pairing": {"ok": True}, "start": start_result}
@@ -4350,6 +4423,85 @@ def _encode_session_cookie(secret: str, payload: Mapping[str, Any]) -> str:
return cookie_value
+_SESSION_AUTHORIZATION_CLAIM_KEYS = (
+ "vibe_instance_id",
+ "vibe_instance_role",
+ "vibe_instance_access_source",
+ "vibe_instance_authorization_revision",
+ "vibe_show_page_id",
+ *_ORGANIZATION_SESSION_CLAIM_KEYS,
+)
+
+
+def _authorization_scope(
+ config: V2Config,
+ claims: Mapping[str, Any],
+) -> tuple[str, str]:
+ if claims.get("vibe_instance_access_source") == "show_page_email":
+ show_page_id = claims.get("vibe_show_page_id")
+ if isinstance(show_page_id, str) and show_page_id:
+ return "show_page", show_page_id
+ return "instance", str(config.remote_access.vibe_cloud.instance_id)
+
+
+def _authorization_claims_from_payload(payload: Mapping[str, Any]) -> dict[str, Any]:
+ claims = {
+ key: payload[key]
+ for key in _SESSION_AUTHORIZATION_CLAIM_KEYS
+ if key in payload
+ }
+ claims_issued_at = payload.get("claims_issued_at")
+ if isinstance(claims_issued_at, int) and not isinstance(claims_issued_at, bool):
+ claims["claims_issued_at"] = claims_issued_at
+ return claims
+
+
+def _authorization_revision_from_claims(claims: Mapping[str, Any]) -> int | None:
+ try:
+ return _normalize_authorization_revision(claims.get(_AUTHORIZATION_REVISION_KEY))
+ except ValueError:
+ return None
+
+
+def _authorization_checked_revision(claims: Mapping[str, Any]) -> int | None:
+ try:
+ checked_revision = _normalize_authorization_revision(
+ claims.get(_AUTHORIZATION_CHECKED_REVISION_KEY)
+ )
+ except ValueError:
+ checked_revision = None
+ if checked_revision is not None:
+ return checked_revision
+ return _authorization_revision_from_claims(claims)
+
+
+def _store_scoped_authorization(
+ config: V2Config,
+ *,
+ reference: str | None,
+ subject: str,
+ email: str,
+ claims: Mapping[str, Any],
+ authorization_state: str,
+ checked_at: int,
+) -> str:
+ from storage import remote_access_authorization_service
+
+ scope_kind, scope_ref = _authorization_scope(config, claims)
+ return remote_access_authorization_service.upsert_scoped(
+ reference=reference,
+ instance_id=str(config.remote_access.vibe_cloud.instance_id),
+ subject=subject,
+ email=email,
+ scope_kind=scope_kind,
+ scope_ref=scope_ref,
+ authorization_state=authorization_state,
+ claims=claims,
+ last_checked_at=checked_at,
+ updated_at=checked_at,
+ )
+
+
def make_session_cookie(
config: V2Config,
email: str,
@@ -4361,44 +4513,90 @@ def make_session_cookie(
if not cloud.session_secret:
raise ValueError("Remote access session secret is not configured")
issued_at = int(time.time())
+ validated_claims = session_claims_from_oidc(config, session_claims)
+ revision = _authorization_revision_from_claims(validated_claims)
+ if revision is not None:
+ try:
+ _replace_authorization_revision(config, revision)
+ except ValueError as exc:
+ raise OAuthCodeExchangeError("stale_authorization_revision") from exc
+ stored_claims = {**validated_claims, "claims_issued_at": issued_at}
+ reference = _store_scoped_authorization(
+ config,
+ reference=None,
+ subject=subject,
+ email=email,
+ claims=stored_claims,
+ authorization_state="current",
+ checked_at=issued_at,
+ )
payload = {
"email": email,
"sub": subject,
"instance_id": cloud.instance_id,
"iat": issued_at,
- "exp": issued_at + SESSION_TTL_SECONDS,
+ "exp": issued_at + PERSONAL_SESSION_TTL_SECONDS,
+ "claims_issued_at": issued_at,
+ _SESSION_BROWSER_ID_KEY: secrets.token_urlsafe(24),
+ _SESSION_AUTHORIZATION_REFERENCE_KEY: reference,
}
- validated_claims = session_claims_from_oidc(config, session_claims)
- if not session_authorization_is_current(config, validated_claims):
- if current_authorization_revision(config) is None:
- raise OAuthCodeExchangeError("authorization_revision_unavailable")
- raise OAuthCodeExchangeError("stale_authorization_revision")
- # Instance roles and optional organization membership must be refreshed
- # through OIDC instead of being slid indefinitely from a local cookie.
- payload["claims_issued_at"] = issued_at
-
- if any(key in validated_claims for key in _ORGANIZATION_SESSION_CLAIM_KEYS):
- from storage import remote_access_authorization_service
+ return _encode_session_cookie(cloud.session_secret, payload)
- reference = secrets.token_urlsafe(24)
- payload[_SESSION_AUTHORIZATION_REFERENCE_KEY] = reference
- cookie_value = _encode_session_cookie(cloud.session_secret, payload)
- remote_access_authorization_service.store(
- reference=reference,
- instance_id=cloud.instance_id,
- subject=subject,
- claims=validated_claims,
- expires_at=issued_at + SESSION_TTL_SECONDS,
- created_at=issued_at,
+
+def _prune_revoked_browser_sessions(now: int) -> None:
+ for session_id in [
+ value
+ for value, expires_at in _REVOKED_BROWSER_SESSIONS.items()
+ if expires_at <= now
+ ]:
+ _REVOKED_BROWSER_SESSIONS.pop(session_id, None)
+
+
+def _legacy_browser_session_id(secret: str, cookie_value: str) -> str:
+ return hmac.new(
+ secret.encode("utf-8"),
+ f"legacy-browser-session:{cookie_value}".encode("utf-8"),
+ hashlib.sha256,
+ ).hexdigest()
+
+
+def revoke_browser_session(payload: Mapping[str, Any]) -> bool:
+ session_id = payload.get(_SESSION_BROWSER_ID_KEY)
+ if not isinstance(session_id, str) or not _SESSION_BROWSER_ID_RE.fullmatch(session_id):
+ return False
+ try:
+ expires_at = int(payload.get("exp", 0))
+ except (TypeError, ValueError):
+ return False
+ with _REVOKED_BROWSER_SESSIONS_LOCK:
+ _prune_revoked_browser_sessions(int(time.time()))
+ _REVOKED_BROWSER_SESSIONS[session_id] = expires_at
+ try:
+ from vibe.sse_broker import broker
+
+ broker.publish(
+ "authorization.session-revoked",
+ {"browser_session_id": session_id},
)
- return cookie_value
+ except Exception:
+ logger.debug("failed to publish browser session revocation", exc_info=True)
+ return True
- payload.update(validated_claims)
- cookie_value = _encode_session_cookie(cloud.session_secret, payload)
- return cookie_value
+def _browser_session_is_revoked(payload: Mapping[str, Any], *, now: int) -> bool:
+ session_id = payload.get(_SESSION_BROWSER_ID_KEY)
+ if session_id is None:
+ return False
+ if not isinstance(session_id, str) or not _SESSION_BROWSER_ID_RE.fullmatch(session_id):
+ return True
+ with _REVOKED_BROWSER_SESSIONS_LOCK:
+ _prune_revoked_browser_sessions(now)
+ return session_id in _REVOKED_BROWSER_SESSIONS
+
+
+def parse_session_identity(config: V2Config, cookie_value: str | None) -> dict[str, Any] | None:
+ """Verify browser identity without evaluating current authorization."""
-def parse_session_cookie(config: V2Config, cookie_value: str | None) -> dict[str, Any] | None:
if not cookie_value or "." not in cookie_value:
return None
if len(cookie_value.encode("utf-8")) > SESSION_COOKIE_MAX_VALUE_BYTES:
@@ -4420,8 +4618,16 @@ def parse_session_cookie(config: V2Config, cookie_value: str | None) -> dict[str
subject = payload.get("sub")
if instance_id != cloud.instance_id or not isinstance(subject, str) or not subject:
return None
+ email = payload.get("email")
+ if not isinstance(email, str) or not email.strip():
+ return None
+ try:
+ issued_at = int(payload.get("iat", 0))
+ expires_at = int(payload.get("exp", 0))
+ except (TypeError, ValueError):
+ return None
current = int(time.time())
- if int(payload.get("exp", 0)) <= current:
+ if issued_at <= 0 or expires_at <= current or expires_at <= issued_at:
return None
authorization_reference = payload.get(_SESSION_AUTHORIZATION_REFERENCE_KEY)
if authorization_reference is not None:
@@ -4429,36 +4635,647 @@ def parse_session_cookie(config: V2Config, cookie_value: str | None) -> dict[str
authorization_reference
):
return None
- try:
- from storage import remote_access_authorization_service
+ browser_session_id = payload.get(_SESSION_BROWSER_ID_KEY)
+ if browser_session_id is not None and (
+ not isinstance(browser_session_id, str)
+ or not _SESSION_BROWSER_ID_RE.fullmatch(browser_session_id)
+ ):
+ return None
+ if browser_session_id is None:
+ payload[_SESSION_BROWSER_ID_KEY] = _legacy_browser_session_id(
+ cloud.session_secret,
+ cookie_value,
+ )
+ if _browser_session_is_revoked(payload, now=current):
+ return None
+ return payload
- stored_claims = remote_access_authorization_service.load(
- reference=authorization_reference,
- instance_id=instance_id,
- subject=subject,
- now=current,
- )
- except Exception:
- logger.warning("remote session authorization lookup failed", exc_info=True)
- return None
- if stored_claims is None:
- return None
- payload.update(stored_claims)
+
+def session_identity_is_current(payload: Mapping[str, Any], *, now: int | None = None) -> bool:
+ current = int(time.time()) if now is None else now
try:
- session_claims_from_oidc(config, payload)
- except OAuthCodeExchangeError:
+ expires_at = int(payload.get("exp", 0))
+ except (TypeError, ValueError):
+ return False
+ return expires_at > current and not _browser_session_is_revoked(payload, now=current)
+
+
+def _load_authorization_record(
+ config: V2Config,
+ identity: Mapping[str, Any],
+ *,
+ now: int,
+) -> dict[str, Any] | None:
+ from storage import remote_access_authorization_service
+
+ instance_id = str(identity.get("instance_id") or "")
+ subject = str(identity.get("sub") or "")
+ reference = identity.get(_SESSION_AUTHORIZATION_REFERENCE_KEY)
+ if isinstance(reference, str):
+ record = remote_access_authorization_service.load_reference_record(
+ reference=reference,
+ instance_id=instance_id,
+ subject=subject,
+ now=now,
+ )
+ if record is not None:
+ return record
+
+ inline_claims = _authorization_claims_from_payload(identity)
+ if not inline_claims:
+ return None
+ try:
+ validated = session_claims_from_oidc(config, inline_claims)
+ checked_at = int(inline_claims.get("claims_issued_at", identity.get("iat", 0)))
+ except (OAuthCodeExchangeError, TypeError, ValueError):
return None
- if not session_authorization_is_current(config, payload):
+ if checked_at <= 0:
return None
+ claims = {**validated, "claims_issued_at": checked_at}
+ scope_kind, scope_ref = _authorization_scope(config, claims)
+ existing = remote_access_authorization_service.load_scoped(
+ instance_id=instance_id,
+ subject=subject,
+ scope_kind=scope_kind,
+ scope_ref=scope_ref,
+ )
+ if existing is not None:
+ return existing
try:
- claims_issued_at = int(payload.get("claims_issued_at", payload.get("iat", 0)))
- except (TypeError, ValueError):
+ stored_reference = _store_scoped_authorization(
+ config,
+ reference=None,
+ subject=subject,
+ email=str(identity.get("email") or ""),
+ claims=claims,
+ authorization_state="current",
+ checked_at=checked_at,
+ )
+ return remote_access_authorization_service.load_reference_record(
+ reference=stored_reference,
+ instance_id=instance_id,
+ subject=subject,
+ now=now,
+ )
+ except Exception:
+ logger.warning("legacy remote authorization migration failed", exc_info=True)
+ return {
+ "id": None,
+ "instance_id": instance_id,
+ "subject": subject,
+ "email": identity.get("email"),
+ "scope_kind": scope_kind,
+ "scope_ref": scope_ref,
+ "authorization_state": "current",
+ "claims": claims,
+ "expires_at": identity.get("exp"),
+ "created_at": checked_at,
+ "last_checked_at": checked_at,
+ "updated_at": checked_at,
+ }
+
+
+def _validated_authorization_payload(
+ config: V2Config,
+ identity: Mapping[str, Any],
+ record: Mapping[str, Any],
+) -> dict[str, Any] | None:
+ claims = record.get("claims")
+ if not isinstance(claims, Mapping):
return None
- if claims_issued_at <= 0:
+ payload = dict(identity)
+ payload.update(claims)
+ reference = record.get("id")
+ if isinstance(reference, str):
+ payload[_SESSION_AUTHORIZATION_REFERENCE_KEY] = reference
+ try:
+ session_claims_from_oidc(config, payload)
+ except OAuthCodeExchangeError:
return None
return payload
+def _authorization_within_grace(record: Mapping[str, Any], *, now: int) -> bool:
+ try:
+ last_checked_at = int(
+ record.get("last_checked_at")
+ or record.get("created_at")
+ or 0
+ )
+ except (TypeError, ValueError):
+ return False
+ age = now - last_checked_at
+ return 0 <= age <= ORGANIZATION_AUTHORIZATION_OUTAGE_GRACE_SECONDS
+
+
+def _authorization_refresh_due(payload: Mapping[str, Any], *, now: int) -> bool:
+ try:
+ issued_at = int(payload.get("claims_issued_at", 0))
+ except (TypeError, ValueError):
+ return True
+ return issued_at <= 0 or now >= issued_at + ORGANIZATION_AUTHORIZATION_REFRESH_SECONDS
+
+
+def _fetch_authorization_context(
+ config: V2Config,
+ identity: Mapping[str, Any],
+ record: Mapping[str, Any] | None,
+ *,
+ now: int,
+ observed_revision: int | None,
+) -> AuthorizationResolution:
+ subject = str(identity.get("sub") or "").strip()
+ email = str(identity.get("email") or "").strip()
+ request_payload: dict[str, Any] = {"sub": subject, "email": email}
+ if record is not None and record.get("scope_kind") == "show_page":
+ request_payload["show_page_id"] = record.get("scope_ref")
+ try:
+ response = _device_json_request(
+ config,
+ "POST",
+ "authorization-context",
+ request_payload,
+ timeout=8.0,
+ )
+ except BackendRequestError as exc:
+ if exc.status == 403 and exc.payload.get("error") == "access_denied":
+ previous_claims = record.get("claims") if record is not None else {}
+ if not isinstance(previous_claims, Mapping):
+ previous_claims = {}
+ revoked_claims = dict(previous_claims)
+ if observed_revision is not None:
+ revoked_claims[_AUTHORIZATION_CHECKED_REVISION_KEY] = observed_revision
+ try:
+ _store_scoped_authorization(
+ config,
+ reference=(
+ str(record.get("id"))
+ if record is not None and record.get("id")
+ else None
+ ),
+ subject=subject,
+ email=email,
+ claims=revoked_claims,
+ authorization_state="revoked",
+ checked_at=now,
+ )
+ except Exception:
+ logger.warning("remote authorization revocation persistence failed", exc_info=True)
+ return AuthorizationResolution("revoked", reason="access_denied")
+ return AuthorizationResolution("unavailable", reason="authorization_context_unavailable")
+ except Exception:
+ return AuthorizationResolution("unavailable", reason="authorization_context_unavailable")
+
+ if response.get("sub") != subject or response.get("email") != email:
+ return AuthorizationResolution("unavailable", reason="authorization_context_invalid")
+ instance_kind = _normalized_instance_kind(response.get("instance_kind"))
+ if instance_kind is None:
+ return AuthorizationResolution("unavailable", reason="instance_kind_unavailable")
+ try:
+ claims = session_claims_from_oidc(config, response)
+ revision = _authorization_revision_from_claims(claims)
+ if revision is not None:
+ _replace_authorization_revision(config, revision)
+ stored_claims = {**claims, "claims_issued_at": now}
+ reference = _store_scoped_authorization(
+ config,
+ reference=(
+ str(record.get("id"))
+ if record is not None and record.get("id")
+ else None
+ ),
+ subject=subject,
+ email=email,
+ claims=stored_claims,
+ authorization_state="current",
+ checked_at=now,
+ )
+ from storage import remote_access_authorization_service
+
+ refreshed_record = remote_access_authorization_service.load_reference_record(
+ reference=reference,
+ instance_id=str(identity.get("instance_id") or ""),
+ subject=subject,
+ now=now,
+ )
+ except Exception:
+ logger.warning("remote authorization context validation failed", exc_info=True)
+ return AuthorizationResolution("unavailable", reason="authorization_context_invalid")
+ config.remote_access.vibe_cloud.instance_kind = instance_kind
+ try:
+ _persist_instance_kind(str(identity.get("instance_id") or ""), instance_kind)
+ except Exception:
+ # The authoritative response and durable context are already valid.
+ # A config write failure must not turn accepted access into an outage;
+ # this in-memory config immediately follows the discovered policy and a
+ # later runtime status/auth refresh can retry the persistent backfill.
+ logger.warning("Remote instance kind backfill failed", exc_info=True)
+ if refreshed_record is None:
+ return AuthorizationResolution("unavailable", reason="authorization_context_persistence_failed")
+ payload = _validated_authorization_payload(config, identity, refreshed_record)
+ if payload is None:
+ return AuthorizationResolution("unavailable", reason="authorization_context_invalid")
+ return AuthorizationResolution(
+ "current",
+ payload=payload,
+ policy=instance_kind,
+ refreshed=True,
+ )
+
+
+def _refresh_authorization_context(
+ config: V2Config,
+ identity: Mapping[str, Any],
+ record: Mapping[str, Any] | None,
+ *,
+ now: int,
+ force: bool = False,
+) -> AuthorizationResolution:
+ key = _authorization_refresh_key(identity, record)
+ with _AUTHORIZATION_REFRESH_LOCK:
+ flight = _AUTHORIZATION_REFRESH_FLIGHTS.get(key)
+ if flight is None:
+ flight_lock = threading.Lock()
+ flight_users = 0
+ else:
+ flight_lock, flight_users = flight
+ _AUTHORIZATION_REFRESH_FLIGHTS[key] = (flight_lock, flight_users + 1)
+ flight_lock.acquire()
+ try:
+ monotonic_now = time.monotonic()
+ with _AUTHORIZATION_REFRESH_LOCK:
+ recent_result = _AUTHORIZATION_REFRESH_RESULTS.get(key)
+ last_failure = _AUTHORIZATION_REFRESH_FAILURES.get(key)
+ observed_revision = (
+ current_authorization_revision(config)
+ if _authorization_revision_sync_configured(config)
+ else None
+ )
+ if (
+ not force
+ and recent_result is not None
+ and monotonic_now - recent_result[0] < AUTHORIZATION_REFRESH_FAILURE_BACKOFF_SECONDS
+ and (
+ observed_revision is None
+ or recent_result[3] == observed_revision
+ )
+ ):
+ from storage import remote_access_authorization_service
+
+ current_record = remote_access_authorization_service.load_scoped(
+ instance_id=key[0],
+ subject=key[1],
+ scope_kind=key[2],
+ scope_ref=key[3],
+ )
+ if recent_result[1] == "revoked":
+ return AuthorizationResolution("revoked", reason="access_denied")
+ if current_record is not None:
+ if current_record.get("authorization_state") == "revoked":
+ return AuthorizationResolution("revoked", reason="access_denied")
+ if recent_result[1] == "current":
+ current_payload = _validated_authorization_payload(
+ config,
+ identity,
+ current_record,
+ )
+ if current_payload is not None:
+ return AuthorizationResolution(
+ "current",
+ payload=current_payload,
+ policy=recent_result[2],
+ refreshed=True,
+ )
+ if (
+ not force
+ and last_failure is not None
+ and monotonic_now - last_failure < AUTHORIZATION_REFRESH_FAILURE_BACKOFF_SECONDS
+ ):
+ return AuthorizationResolution("unavailable", reason="authorization_refresh_backoff")
+ refreshed = _fetch_authorization_context(
+ config,
+ identity,
+ record,
+ now=now,
+ observed_revision=observed_revision,
+ )
+ completed_at = time.monotonic()
+ with _AUTHORIZATION_REFRESH_LOCK:
+ _AUTHORIZATION_REFRESH_RESULTS.pop(key, None)
+ if refreshed.state == "unavailable":
+ _AUTHORIZATION_REFRESH_FAILURES[key] = completed_at
+ if len(_AUTHORIZATION_REFRESH_FAILURES) > 1024:
+ cutoff = completed_at - AUTHORIZATION_REFRESH_FAILURE_BACKOFF_SECONDS
+ for stale_key in [
+ item
+ for item, failed_at in _AUTHORIZATION_REFRESH_FAILURES.items()
+ if failed_at < cutoff
+ ]:
+ _AUTHORIZATION_REFRESH_FAILURES.pop(stale_key, None)
+ else:
+ _AUTHORIZATION_REFRESH_FAILURES.pop(key, None)
+ if refreshed.state in {"current", "revoked"}:
+ refreshed_revision = (
+ observed_revision
+ if refreshed.state == "revoked"
+ else _authorization_revision_from_claims(refreshed.payload)
+ if refreshed.payload is not None
+ else None
+ )
+ _AUTHORIZATION_REFRESH_RESULTS[key] = (
+ completed_at,
+ refreshed.state,
+ refreshed.policy,
+ refreshed_revision,
+ )
+ if len(_AUTHORIZATION_REFRESH_RESULTS) > 1024:
+ cutoff = completed_at - AUTHORIZATION_REFRESH_FAILURE_BACKOFF_SECONDS
+ for stale_key in [
+ item
+ for item, (finished_at, _state, _policy, _revision) in _AUTHORIZATION_REFRESH_RESULTS.items()
+ if finished_at < cutoff
+ ]:
+ _AUTHORIZATION_REFRESH_RESULTS.pop(stale_key, None)
+ return refreshed
+ finally:
+ flight_lock.release()
+ with _AUTHORIZATION_REFRESH_LOCK:
+ current_flight = _AUTHORIZATION_REFRESH_FLIGHTS.get(key)
+ if current_flight is not None and current_flight[0] is flight_lock:
+ if current_flight[1] <= 1:
+ _AUTHORIZATION_REFRESH_FLIGHTS.pop(key, None)
+ else:
+ _AUTHORIZATION_REFRESH_FLIGHTS[key] = (
+ flight_lock,
+ current_flight[1] - 1,
+ )
+
+
+def _authorization_refresh_key(
+ identity: Mapping[str, Any],
+ record: Mapping[str, Any] | None,
+) -> tuple[str, str, str, str]:
+ scope_kind = str(record.get("scope_kind") or "instance") if record else "instance"
+ scope_ref = (
+ str(record.get("scope_ref") or identity.get("instance_id") or "")
+ if record
+ else str(identity.get("instance_id") or "")
+ )
+ return (
+ str(identity.get("instance_id") or ""),
+ str(identity.get("sub") or ""),
+ scope_kind,
+ scope_ref,
+ )
+
+
+def _schedule_authorization_refresh(
+ config: V2Config,
+ identity: Mapping[str, Any],
+ record: Mapping[str, Any] | None,
+ *,
+ now: int,
+) -> None:
+ key = _authorization_refresh_key(identity, record)
+ with _AUTHORIZATION_BACKGROUND_REFRESH_LOCK:
+ if key in _AUTHORIZATION_BACKGROUND_REFRESHES:
+ return
+ _AUTHORIZATION_BACKGROUND_REFRESHES.add(key)
+
+ def run() -> None:
+ try:
+ _refresh_authorization_context(config, identity, record, now=now)
+ except Exception:
+ logger.warning("Background remote authorization refresh failed", exc_info=True)
+ finally:
+ with _AUTHORIZATION_BACKGROUND_REFRESH_LOCK:
+ _AUTHORIZATION_BACKGROUND_REFRESHES.discard(key)
+
+ threading.Thread(
+ target=run,
+ name="remote-authorization-refresh",
+ daemon=True,
+ ).start()
+
+
+def resolve_current_authorization(
+ config: V2Config,
+ identity: Mapping[str, Any],
+ *,
+ now: int | None = None,
+ allow_refresh: bool = True,
+ refresh_revoked: bool = False,
+) -> AuthorizationResolution:
+ """Resolve current access without turning control-plane failure into logout."""
+
+ revision_now = None if now is None else float(now)
+ current = int(time.time()) if now is None else now
+ if not session_identity_is_current(identity, now=current):
+ return AuthorizationResolution("invalid_identity", reason="identity_expired")
+ try:
+ record = _load_authorization_record(config, identity, now=current)
+ except Exception:
+ logger.warning("remote authorization record load failed", exc_info=True)
+ return AuthorizationResolution(
+ "unavailable",
+ reason="authorization_record_unavailable",
+ )
+ if (
+ record is None
+ and isinstance(identity.get(_SESSION_AUTHORIZATION_REFERENCE_KEY), str)
+ ):
+ return AuthorizationResolution(
+ "invalid_identity",
+ reason="authorization_record_missing",
+ )
+ if record is not None and record.get("authorization_state") == "revoked":
+ claims = record.get("claims")
+ record_revision = (
+ _authorization_checked_revision(claims)
+ if isinstance(claims, Mapping)
+ else None
+ )
+ observed_revision = (
+ current_authorization_revision(config, now=revision_now)
+ if _authorization_revision_sync_configured(config)
+ else None
+ )
+ authority_changed = (
+ observed_revision is not None
+ and record_revision is not None
+ and observed_revision != record_revision
+ )
+ if allow_refresh and (refresh_revoked or authority_changed):
+ refreshed = _refresh_authorization_context(
+ config,
+ identity,
+ record,
+ now=current,
+ force=refresh_revoked,
+ )
+ if refreshed.state != "unavailable":
+ return refreshed
+ return AuthorizationResolution("revoked", reason="access_denied")
+ payload = (
+ _validated_authorization_payload(config, identity, record)
+ if record is not None
+ else None
+ )
+ if payload is None:
+ return (
+ _refresh_authorization_context(config, identity, record, now=current)
+ if allow_refresh
+ else AuthorizationResolution("unavailable", reason="authorization_context_missing")
+ )
+
+ instance_kind = _normalized_instance_kind(config.remote_access.vibe_cloud.instance_kind)
+ signed_revision = _authorization_revision_from_claims(payload)
+ current_revision = (
+ current_authorization_revision(config, now=revision_now)
+ if _authorization_revision_sync_configured(config)
+ else None
+ )
+
+ if instance_kind == "personal":
+ if (
+ current_revision is not None
+ and signed_revision is not None
+ and current_revision != signed_revision
+ and allow_refresh
+ ):
+ _schedule_authorization_refresh(config, identity, record, now=current)
+ return AuthorizationResolution("current", payload=payload, policy="personal")
+
+ if instance_kind == "organization":
+ revision_unknown = current_revision is None or signed_revision is None
+ revision_changed = (
+ current_revision is not None
+ and signed_revision is not None
+ and current_revision != signed_revision
+ )
+ scheduled_refresh = _authorization_refresh_due(payload, now=current)
+ within_grace = _authorization_within_grace(record, now=current)
+ if (
+ scheduled_refresh
+ and not revision_unknown
+ and not revision_changed
+ and within_grace
+ and allow_refresh
+ ):
+ _schedule_authorization_refresh(config, identity, record, now=current)
+ return AuthorizationResolution(
+ "current",
+ payload=payload,
+ policy="organization",
+ reason="authorization_refresh_scheduled",
+ )
+ if (revision_changed or scheduled_refresh) and allow_refresh:
+ refreshed = _refresh_authorization_context(config, identity, record, now=current)
+ if refreshed.state != "unavailable":
+ return refreshed
+ if revision_unknown or revision_changed or scheduled_refresh:
+ if within_grace:
+ return AuthorizationResolution(
+ "current",
+ payload=payload,
+ policy="organization",
+ reason="authorization_grace",
+ )
+ return AuthorizationResolution(
+ "unavailable",
+ policy="organization",
+ reason="authorization_grace_expired",
+ )
+ return AuthorizationResolution("current", payload=payload, policy="organization")
+
+ # Pre-kind pairings keep the former strict freshness contract until a
+ # successful backchannel response fills the kind. They fail unavailable,
+ # never as a fake browser logout.
+ if not _authorization_revision_sync_configured(config):
+ return AuthorizationResolution("current", payload=payload, policy=None)
+ legacy_current = (
+ current_revision is not None
+ and signed_revision == current_revision
+ and not _authorization_refresh_due(payload, now=current)
+ )
+ if legacy_current:
+ return AuthorizationResolution("current", payload=payload, policy=None)
+ if allow_refresh:
+ return _refresh_authorization_context(config, identity, record, now=current)
+ return AuthorizationResolution("unavailable", reason="instance_kind_unavailable")
+
+
+async def resolve_current_authorization_async(
+ config: V2Config,
+ identity: Mapping[str, Any],
+ *,
+ now: int | None = None,
+ allow_refresh: bool = True,
+ refresh_revoked: bool = False,
+) -> AuthorizationResolution:
+ import asyncio
+
+ return await asyncio.to_thread(
+ resolve_current_authorization,
+ config,
+ identity,
+ now=now,
+ allow_refresh=allow_refresh,
+ refresh_revoked=refresh_revoked,
+ )
+
+
+def renew_session_cookie(
+ config: V2Config,
+ payload: Mapping[str, Any],
+ *,
+ now: int | None = None,
+) -> str:
+ """Slide browser identity without pretending cached claims were refreshed."""
+
+ cloud = config.remote_access.vibe_cloud
+ if not cloud.session_secret:
+ raise ValueError("Remote access session secret is not configured")
+ current = int(time.time()) if now is None else now
+ reference = payload.get(_SESSION_AUTHORIZATION_REFERENCE_KEY)
+ if not isinstance(reference, str):
+ claims = _authorization_claims_from_payload(payload)
+ checked_at = int(payload.get("claims_issued_at", payload.get("iat", current)))
+ reference = _store_scoped_authorization(
+ config,
+ reference=None,
+ subject=str(payload.get("sub") or ""),
+ email=str(payload.get("email") or ""),
+ claims=claims,
+ authorization_state="current",
+ checked_at=checked_at,
+ )
+ browser_session_id = payload.get(_SESSION_BROWSER_ID_KEY)
+ if not isinstance(browser_session_id, str):
+ browser_session_id = secrets.token_urlsafe(24)
+ identity = {
+ "email": str(payload.get("email") or ""),
+ "sub": str(payload.get("sub") or ""),
+ "instance_id": str(payload.get("instance_id") or ""),
+ "iat": current,
+ "exp": current + PERSONAL_SESSION_TTL_SECONDS,
+ "claims_issued_at": int(payload.get("claims_issued_at", payload.get("iat", current))),
+ _SESSION_BROWSER_ID_KEY: browser_session_id,
+ _SESSION_AUTHORIZATION_REFERENCE_KEY: reference,
+ }
+ return _encode_session_cookie(cloud.session_secret, identity)
+
+
+def parse_session_cookie(config: V2Config, cookie_value: str | None) -> dict[str, Any] | None:
+ """Compatibility wrapper returning only a currently authorized session."""
+
+ identity = parse_session_identity(config, cookie_value)
+ if identity is None:
+ return None
+ result = resolve_current_authorization(config, identity)
+ return result.payload if result.current else None
+
+
def validate_session_cookie(config: V2Config, cookie_value: str | None) -> bool:
return parse_session_cookie(config, cookie_value) is not None
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 0fb4ab949..ad192b7f0 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -150,7 +150,10 @@ _SHOW_RUNTIME_COMPRESSIBLE_MIN_BYTES = 1024
TERMINAL_ENABLED_ENV = "VIBE_UI_ENABLE_TERMINAL"
TERMINAL_IDLE_TIMEOUT_ENV = "VIBE_UI_TERMINAL_IDLE_TIMEOUT_SECONDS"
TERMINAL_MAX_SESSIONS_ENV = "VIBE_UI_TERMINAL_MAX_SESSIONS"
-_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE = 4401
+_AUTHORIZATION_LOGIN_REQUIRED_WEBSOCKET_CLOSE_CODE = 4401
+_AUTHORIZATION_REVOKED_WEBSOCKET_CLOSE_CODE = 4403
+_AUTHORIZATION_UNAVAILABLE_WEBSOCKET_CLOSE_CODE = 4503
+_AUTHORIZATION_CHANGED_WEBSOCKET_CLOSE_CODE = 1012
_AUTHORIZATION_REVISION_RECHECK_SECONDS = 1.0
_TRUE_BOOL_STRINGS = {"1", "true", "yes", "on"}
@@ -1320,12 +1323,7 @@ def memory_ui_user_key() -> str | None:
if not source or not _same_origin(source, _current_origin()):
return None
try:
- from vibe import remote_access
-
- payload = remote_access.parse_session_cookie(
- config,
- request.cookies.get(remote_access.SESSION_COOKIE_NAME),
- )
+ payload = _resolved_remote_session_payload(config)
except Exception:
return None
subject = payload.get("sub") if isinstance(payload, dict) else None
@@ -1334,6 +1332,22 @@ def memory_ui_user_key() -> str | None:
return f"avibe:remote:{subject.strip()}"
+def _resolved_remote_session_payload(config: V2Config) -> dict[str, Any] | None:
+ existing = getattr(g, "remote_session_payload", None)
+ if isinstance(existing, dict):
+ return existing
+ from vibe import remote_access
+
+ identity = remote_access.parse_session_identity(
+ config,
+ request.cookies.get(remote_access.SESSION_COOKIE_NAME),
+ )
+ if identity is None:
+ return None
+ resolution = remote_access.resolve_current_authorization(config, identity)
+ return resolution.payload if resolution.current else None
+
+
def _normalized_host(value: str | None) -> str:
raw_host = (value or "").lower().strip()
if raw_host.startswith("[") and "]" in raw_host:
@@ -2310,14 +2324,31 @@ def enforce_remote_access_cookie():
return jsonify({"ok": False, "error": "remote_access_disabled"}), 503
if not config.remote_access.vibe_cloud.session_secret:
return jsonify({"ok": False, "error": "remote_access_session_secret_missing"}), 503
- payload = remote_access.parse_session_cookie(config, request.cookies.get(remote_access.SESSION_COOKIE_NAME))
+ identity = remote_access.parse_session_identity(
+ config,
+ request.cookies.get(remote_access.SESSION_COOKIE_NAME),
+ )
+ if identity is not None:
+ resolution = remote_access.resolve_current_authorization(config, identity)
+ if resolution.state == "revoked":
+ if _is_ui_static_request():
+ g.remote_session_identity = identity
+ g.remote_authorization_resolution = resolution
+ return None
+ return jsonify({"ok": False, "error": "remote_access_revoked"}), 403
+ if resolution.state == "unavailable":
+ if _is_ui_static_request():
+ g.remote_session_identity = identity
+ g.remote_authorization_resolution = resolution
+ return None
+ return jsonify(
+ {"ok": False, "error": "remote_access_authorization_unavailable"}
+ ), 503
+ payload = resolution.payload if resolution.current else None
+ else:
+ resolution = None
+ payload = None
if payload is not None:
- if remote_access.session_needs_authorization_refresh(payload):
- if request.method == "GET" and not request.path.startswith("/api/"):
- if _auth_rate_limited():
- return _auth_rate_limit_response()
- return _redirect_to_vibe_cloud_login(config)
- return jsonify({"ok": False, "error": "remote_access_authorization_refresh_required"}), 401
context = context_from_session_payload(payload)
if request.method == "GET" and context.instance_access_source != "show_page_email":
show_page_id = _show_page_id_from_private_route(request.path)
@@ -2339,8 +2370,9 @@ def enforce_remote_access_cookie():
return _auth_rate_limit_response()
return _redirect_to_vibe_cloud_login(config, show_page_reauth=True)
g.authorization_context = context
+ g.remote_session_identity = identity
g.remote_session_payload = payload
- g.remote_authorization_refresh_at = remote_access.session_authorization_refresh_deadline(payload)
+ g.remote_authorization_resolution = resolution
if remote_access.session_needs_renewal(payload):
g.remote_session_renew = payload
return None
@@ -2364,13 +2396,9 @@ def enforce_show_page_email_scope():
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),
- )
+ payload = _resolved_remote_session_payload(config)
if payload is not None:
context = context_from_session_payload(payload)
if context is None or context.instance_access_source != "show_page_email":
@@ -2778,16 +2806,9 @@ def renew_remote_access_cookie(response: Response) -> Response:
if not isinstance(renew, dict):
return response
- email = str(renew.get("email", ""))
- subject = str(renew.get("sub", ""))
try:
- session_cookie = remote_access.make_session_cookie(
- config,
- email,
- subject,
- session_claims=renew,
- )
- except remote_access.OAuthCodeExchangeError:
+ session_cookie = remote_access.renew_session_cookie(config, renew)
+ except (remote_access.OAuthCodeExchangeError, TypeError, ValueError):
return response
response.set_cookie(
remote_access.SESSION_COOKIE_NAME,
@@ -2948,20 +2969,52 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
if not _show_runtime_hmr_origin_allowed(websocket):
await websocket.close(code=1008)
return
- if not _show_runtime_websocket_authorized(
- websocket,
- minimum_role="viewer",
- project_session_id=session_id,
- ):
- await websocket.close(code=1008)
- return
+ remote_config = _load_remote_access_config()
+ local_request = _websocket_is_local_request(websocket, remote_config)
+ remote_identity = None
+ remote_payload = None
+ remote_session_cookie = None
+ remote_request_host = None
+ authorization_context = None
+ if not local_request:
+ from vibe import remote_access
+
+ remote_session_cookie = getattr(websocket, "cookies", {}).get(
+ remote_access.SESSION_COOKIE_NAME
+ )
+ remote_request_host = _websocket_normalized_host(websocket)
+ remote_identity, resolution = await _remote_access_websocket_authorization(
+ websocket,
+ remote_config,
+ )
+ if resolution is None or not resolution.current:
+ await _close_websocket_for_authorization(
+ websocket,
+ resolution.state if resolution is not None else "invalid_identity",
+ subprotocol="vite-hmr",
+ )
+ return
+ remote_payload = resolution.payload
+ from vibe.authorization import context_from_session_payload
+
+ authorization_context = context_from_session_payload(remote_payload)
+ if not _websocket_context_authorized(
+ authorization_context,
+ minimum_role="viewer",
+ project_session_id=session_id,
+ ):
+ await websocket.close(code=1008)
+ return
store = ShowPageStore()
try:
try:
page = store.require_access(
session_id,
- user_context=_show_runtime_websocket_resource_context(websocket),
+ user_context=_show_runtime_websocket_resource_context(
+ websocket,
+ payload=remote_payload,
+ ),
)
except ShowPageError:
await websocket.close(code=1008)
@@ -2975,20 +3028,6 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
finally:
store.close()
- authorization_refresh_at = None
- authorization_context = None
- remote_config = _load_remote_access_config()
- remote_payload = _remote_access_websocket_session_claims(websocket, remote_config)
- if remote_payload is None and not _websocket_is_local_request(websocket, remote_config):
- await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
- return
- if remote_payload is not None:
- from vibe import remote_access
- from vibe.authorization import context_from_session_payload
-
- authorization_refresh_at = remote_access.session_authorization_refresh_deadline(remote_payload)
- authorization_context = context_from_session_payload(remote_payload)
-
access_sub_id = None
access_queue = None
if authorization_context is not None:
@@ -3017,9 +3056,15 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
)
authorization_revision_task = (
asyncio.create_task(
- _wait_for_remote_session_authorization_loss(remote_config, remote_payload)
+ _wait_for_remote_session_authorization_loss(
+ remote_config,
+ remote_identity,
+ remote_payload,
+ session_cookie=remote_session_cookie,
+ request_host=remote_request_host,
+ )
)
- if remote_config is not None and remote_payload is not None
+ if remote_config is not None and remote_identity is not None and remote_payload is not None
else None
)
try:
@@ -3028,29 +3073,20 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
waiters.add(revocation_task)
if authorization_revision_task is not None:
waiters.add(authorization_revision_task)
- timeout = (
- None
- if authorization_refresh_at is None
- else max(0.0, authorization_refresh_at - time.time())
- )
done, _pending = await asyncio.wait(
waiters,
- timeout=timeout,
return_when=asyncio.FIRST_COMPLETED,
)
- if not done:
- logger.info("show_runtime.authorization_refresh session=%s", session_id)
- await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
- elif proxy_task in done:
+ if proxy_task in done:
await proxy_task
elif authorization_revision_task is not None and authorization_revision_task in done:
- await authorization_revision_task
- logger.info("show_runtime.authorization_revoked session=%s", session_id)
- await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
+ outcome = await authorization_revision_task
+ logger.info("show_runtime.authorization_%s session=%s", outcome, session_id)
+ await websocket.close(code=_authorization_websocket_close_code(outcome))
else:
await revocation_task
logger.info("show_runtime.authorization_revoked session=%s", session_id)
- await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
+ await websocket.close(code=_AUTHORIZATION_REVOKED_WEBSOCKET_CLOSE_CODE)
except Exception:
logger.debug("Show runtime HMR websocket unavailable", exc_info=True)
await websocket.close(code=1011)
@@ -3112,29 +3148,45 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):
if not _terminal_origin_allowed(websocket):
await websocket.close(code=1008)
return
- if not _show_runtime_websocket_authorized(
- websocket,
- minimum_role="editor",
- ):
- await websocket.close(code=1008)
- return
-
config = _load_remote_access_config()
- remote_payload = _remote_access_websocket_session_claims(websocket, config)
- if remote_payload is None and not _websocket_is_local_request(websocket, config):
- await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
- return
+ local_request = _websocket_is_local_request(websocket, config)
+ remote_identity = None
+ remote_payload = None
+ remote_session_cookie = None
+ remote_request_host = None
+ if not local_request:
+ from vibe import remote_access
+
+ remote_session_cookie = getattr(websocket, "cookies", {}).get(
+ remote_access.SESSION_COOKIE_NAME
+ )
+ remote_request_host = _websocket_normalized_host(websocket)
+ remote_identity, resolution = await _remote_access_websocket_authorization(
+ websocket,
+ config,
+ )
+ if resolution is None or not resolution.current:
+ await _close_websocket_for_authorization(
+ websocket,
+ resolution.state if resolution is not None else "invalid_identity",
+ )
+ return
+ remote_payload = resolution.payload
+ from vibe.authorization import context_from_session_payload
+
+ if not _websocket_context_authorized(
+ context_from_session_payload(remote_payload),
+ minimum_role="editor",
+ ):
+ await websocket.close(code=1008)
+ return
await websocket.accept()
remote_addr = _websocket_client_host(websocket) or "unknown"
remote_subject = None
- authorization_refresh_at = None
if remote_payload is not None:
- from vibe import remote_access
-
subject = str(remote_payload.get("sub") or "").strip()
email = str(remote_payload.get("email") or "").strip()
remote_subject = subject or email or None
- authorization_refresh_at = remote_access.session_authorization_refresh_deadline(remote_payload)
effective_session_id = _terminal_effective_session_id(session_id, remote_subject)
session_ref = _terminal_session_log_ref(effective_session_id)
logger.info("terminal.session_open session_ref=%s remote_addr=%s", session_ref, remote_addr)
@@ -3156,31 +3208,28 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):
)
authorization_revision_task = (
asyncio.create_task(
- _wait_for_remote_session_authorization_loss(config, remote_payload)
+ _wait_for_remote_session_authorization_loss(
+ config,
+ remote_identity,
+ remote_payload,
+ session_cookie=remote_session_cookie,
+ request_host=remote_request_host,
+ )
)
- if config is not None and remote_payload is not None
+ if config is not None and remote_identity is not None and remote_payload is not None
else None
)
waiters = {handler_task}
if authorization_revision_task is not None:
waiters.add(authorization_revision_task)
- timeout = (
- None
- if authorization_refresh_at is None
- else max(0.0, authorization_refresh_at - time.time())
- )
done, _pending = await asyncio.wait(
waiters,
- timeout=timeout,
return_when=asyncio.FIRST_COMPLETED,
)
- if not done:
- logger.info("terminal.authorization_refresh session_ref=%s", session_ref)
- await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
- elif authorization_revision_task is not None and authorization_revision_task in done:
- await authorization_revision_task
- logger.info("terminal.authorization_revoked session_ref=%s", session_ref)
- await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
+ if authorization_revision_task is not None and authorization_revision_task in done:
+ outcome = await authorization_revision_task
+ logger.info("terminal.authorization_%s session_ref=%s", outcome, session_ref)
+ await websocket.close(code=_authorization_websocket_close_code(outcome))
else:
await handler_task
except TerminalServiceError as exc:
@@ -3216,17 +3265,19 @@ async def terminal_session_delete(session_id: str):
terminal_request = _terminal_http_request_adapter()
if not _terminal_origin_allowed(terminal_request):
return jsonify({"ok": False, "error": "terminal_origin_forbidden"}), 403
- if not _show_runtime_websocket_authorized(
- terminal_request,
- # Closing a terminal session is allowed for any authenticated runtime
- # viewer; the subject-scoped effective ID below prevents terminating a
- # different user's session. Opening an interactive terminal remains an
- # Editor-only operation in ``terminal_websocket``.
- minimum_role="viewer",
- ):
+ context = getattr(g, "authorization_context", None)
+ # Closing a terminal session is allowed for any authenticated runtime
+ # viewer; the subject-scoped effective ID below prevents terminating a
+ # different user's session. Opening remains Editor-only.
+ if context is None or not context.has_role("viewer"):
return jsonify({"ok": False, "error": "terminal_unauthorized"}), 403
- remote_subject = _remote_access_websocket_subject(terminal_request)
+ remote_payload = getattr(g, "remote_session_payload", None)
+ remote_subject = None
+ if isinstance(remote_payload, Mapping):
+ subject = str(remote_payload.get("sub") or "").strip()
+ email = str(remote_payload.get("email") or "").strip()
+ remote_subject = subject or email or None
effective_session_id = _terminal_effective_session_id(session_id, remote_subject)
session_ref = _terminal_session_log_ref(effective_session_id)
terminated = await get_terminal_service().terminate(effective_session_id)
@@ -3266,6 +3317,19 @@ def _show_runtime_websocket_authorized(
from vibe.authorization import context_from_session_payload
context = context_from_session_payload(payload)
+ return _websocket_context_authorized(
+ context,
+ minimum_role=minimum_role,
+ project_session_id=project_session_id,
+ )
+
+
+def _websocket_context_authorized(
+ context: Any,
+ *,
+ minimum_role: str,
+ project_session_id: str | None = None,
+) -> bool:
if not context.has_role(minimum_role):
return False
if context.instance_access_source == "show_page_email":
@@ -3356,15 +3420,39 @@ def _show_page_resource_access_allowed(context: Any, session_id: str) -> bool:
async def _wait_for_remote_session_authorization_loss(
config: V2Config,
- payload: Mapping[str, Any],
-) -> None:
+ identity: Mapping[str, Any],
+ payload: Mapping[str, Any] | None = None,
+ *,
+ session_cookie: str | None,
+ request_host: str | None,
+) -> str:
+ """Return the terminal state for one accepted remote socket."""
+
from vibe import remote_access
+ from vibe.authorization import context_from_session_payload
- while remote_access.session_authorization_is_current(config, payload):
+ if payload is None:
+ payload = identity
+ initial_context = context_from_session_payload(payload)
+ while True:
await asyncio.sleep(_AUTHORIZATION_REVISION_RECHECK_SECONDS)
+ resolution = await _live_remote_authorization_resolution(
+ config,
+ identity,
+ session_cookie=session_cookie,
+ request_host=request_host,
+ )
+ if resolution.state != "current" or resolution.payload is None:
+ return resolution.state
+ if context_from_session_payload(resolution.payload) != initial_context:
+ return "changed"
-def _show_runtime_websocket_resource_context(websocket: Any):
+def _show_runtime_websocket_resource_context(
+ websocket: Any,
+ *,
+ payload: Mapping[str, Any] | None = None,
+):
"""Build the ACL context from the same signed session used by the socket gate."""
from storage import resource_access_service
@@ -3372,7 +3460,8 @@ def _show_runtime_websocket_resource_context(websocket: Any):
config = _load_remote_access_config()
if config is None or _websocket_is_local_request(websocket, config):
return resource_access_service.ResourceUserContext(instance_role="owner")
- payload = _remote_access_websocket_session_payload(websocket, config)
+ if payload is None:
+ payload = _remote_access_websocket_session_payload(websocket, config)
if payload is None:
return resource_access_service.ResourceUserContext()
return _request_authorization_context(
@@ -3390,19 +3479,156 @@ def _show_runtime_hmr_origin_allowed(websocket: Any) -> bool:
return _websocket_origin_matches_effective_request(websocket)
-def _remote_access_websocket_session_payload(websocket: Any, config: V2Config | None) -> dict[str, Any] | None:
- payload = _remote_access_websocket_session_claims(websocket, config)
- if payload is None:
- return None
+def _authorization_websocket_close_code(state: str) -> int:
+ if state == "revoked":
+ return _AUTHORIZATION_REVOKED_WEBSOCKET_CLOSE_CODE
+ if state == "unavailable":
+ return _AUTHORIZATION_UNAVAILABLE_WEBSOCKET_CLOSE_CODE
+ if state == "changed":
+ return _AUTHORIZATION_CHANGED_WEBSOCKET_CLOSE_CODE
+ return _AUTHORIZATION_LOGIN_REQUIRED_WEBSOCKET_CLOSE_CODE
+
+
+async def _close_websocket_for_authorization(
+ websocket: Any,
+ state: str,
+ *,
+ subprotocol: str | None = None,
+) -> None:
+ if subprotocol is None:
+ await websocket.accept()
+ else:
+ await websocket.accept(subprotocol=subprotocol)
+ await websocket.close(code=_authorization_websocket_close_code(state))
+
+
+def _remote_authorization_sse_frame(state: str) -> str:
+ error = {
+ "revoked": "remote_access_revoked",
+ "unavailable": "remote_access_authorization_unavailable",
+ "changed": "remote_access_authorization_changed",
+ }.get(state, "remote_access_login_required")
+ return (
+ "event: remote.authorization\n"
+ f"data: {json.dumps({'state': state, 'error': error}, separators=(',', ':'))}\n\n"
+ )
+
+
+async def _remote_stream_authorization_state(
+ config: V2Config,
+ identity: Mapping[str, Any],
+ initial_payload: Mapping[str, Any],
+ *,
+ session_cookie: str | None,
+ request_host: str | None,
+) -> str:
+ from vibe.authorization import context_from_session_payload
+
+ resolution = await _live_remote_authorization_resolution(
+ config,
+ identity,
+ session_cookie=session_cookie,
+ request_host=request_host,
+ )
+ if not resolution.current or resolution.payload is None:
+ return resolution.state
+ if context_from_session_payload(resolution.payload) != context_from_session_payload(initial_payload):
+ return "changed"
+ return "current"
+
+
+async def _live_remote_authorization_resolution(
+ config: V2Config,
+ identity: Mapping[str, Any],
+ *,
+ session_cookie: str | None,
+ request_host: str | None,
+):
+ """Revalidate the accepted remote session before refreshing its authority."""
+
from vibe import remote_access
- if remote_access.session_needs_authorization_refresh(payload):
- return None
- return payload
+ try:
+ live_config = await asyncio.to_thread(V2Config.load)
+ except Exception:
+ logger.warning("live remote authorization config reload failed", exc_info=True)
+ return remote_access.AuthorizationResolution(
+ "unavailable",
+ reason="remote_access_config_unavailable",
+ )
+
+ cloud = live_config.remote_access.vibe_cloud
+ if not cloud.enabled or not cloud.session_secret:
+ return remote_access.AuthorizationResolution(
+ "invalid_identity",
+ reason=(
+ "remote_access_disabled"
+ if not cloud.enabled
+ else "remote_access_session_secret_missing"
+ ),
+ )
+ if not request_host or not _remote_access_host_allowed(live_config, request_host):
+ return remote_access.AuthorizationResolution(
+ "invalid_identity",
+ reason="remote_access_host_mismatch",
+ )
+ live_identity = remote_access.parse_session_identity(live_config, session_cookie)
+ if live_identity is None or live_identity != dict(identity):
+ return remote_access.AuthorizationResolution(
+ "invalid_identity",
+ reason="identity_invalid",
+ )
+ return await remote_access.resolve_current_authorization_async(
+ live_config,
+ live_identity,
+ )
+
+
+async def _remote_access_websocket_authorization(
+ websocket: Any,
+ config: V2Config | None,
+) -> tuple[dict[str, Any] | None, Any]:
+ from vibe import remote_access
+
+ if config is None or _websocket_is_local_request(websocket, config):
+ return None, None
+ if not _remote_access_host_allowed(config, _websocket_normalized_host(websocket)):
+ return None, remote_access.AuthorizationResolution(
+ "invalid_identity",
+ reason="remote_access_host_mismatch",
+ )
+ cloud = config.remote_access.vibe_cloud
+ if not cloud.enabled or not cloud.session_secret:
+ return None, remote_access.AuthorizationResolution(
+ "invalid_identity",
+ reason=(
+ "remote_access_disabled"
+ if not cloud.enabled
+ else "remote_access_session_secret_missing"
+ ),
+ )
+ cookie_value = websocket.cookies.get(remote_access.SESSION_COOKIE_NAME)
+ identity = remote_access.parse_session_identity(
+ config,
+ cookie_value,
+ )
+ if identity is None:
+ return None, remote_access.AuthorizationResolution(
+ "invalid_identity",
+ reason="identity_invalid",
+ )
+ resolution = await remote_access.resolve_current_authorization_async(config, identity)
+ return identity, resolution
+
+
+def _remote_access_websocket_session_payload(websocket: Any, config: V2Config | None) -> dict[str, Any] | None:
+ """Compatibility sync helper for tests and non-ASGI adapters."""
+
+ return _remote_access_websocket_session_claims(websocket, config)
def _remote_access_websocket_session_claims(websocket: Any, config: V2Config | None) -> dict[str, Any] | None:
- """Return valid signed remote claims without applying their refresh deadline."""
+ """Return current remote claims for synchronous compatibility callers."""
if config is None or _websocket_is_local_request(websocket, config):
return None
@@ -3412,11 +3638,14 @@ def _remote_access_websocket_session_claims(websocket: Any, config: V2Config | N
if not config.remote_access.vibe_cloud.enabled or not config.remote_access.vibe_cloud.session_secret:
return None
- payload = remote_access.parse_session_cookie(
+ identity = remote_access.parse_session_identity(
config,
websocket.cookies.get(remote_access.SESSION_COOKIE_NAME),
)
- return payload
+ if identity is None:
+ return None
+ resolution = remote_access.resolve_current_authorization(config, identity)
+ return resolution.payload if resolution.current else None
def _remote_access_websocket_subject(websocket: Any) -> str | None:
@@ -5525,20 +5754,15 @@ def _web_push_user_key() -> str:
not yet have a user identity, so they share the local install namespace.
Subscription identity is durable (#1434): a still-valid session cookie
keeps attributing subscriptions and test sends to its subject across
- sliding-session renewal. Confirmed revocation is enforced by
- ``parse_session_cookie`` itself (signature, expiry, and current
- authorization revision), so no separate interactive-refresh cutoff is
- applied here.
+ sliding-session renewal. The request's shared authorization resolver
+ enforces confirmed revocation, so no separate interactive-refresh cutoff
+ is applied here.
"""
config = _load_remote_access_config()
if config is not None:
try:
- from vibe import remote_access
-
- payload = remote_access.parse_session_cookie(
- config, request.cookies.get(remote_access.SESSION_COOKIE_NAME)
- )
+ payload = _resolved_remote_session_payload(config)
if payload and payload.get("sub"):
return f"remote:{payload['sub']}"
except Exception:
@@ -5591,12 +5815,7 @@ def _workbench_memory_user_id() -> str | None:
if config is None:
return None
try:
- from vibe import remote_access
-
- payload = remote_access.parse_session_cookie(
- config,
- request.cookies.get(remote_access.SESSION_COOKIE_NAME),
- )
+ payload = _resolved_remote_session_payload(config)
except Exception:
return None
subject = payload.get("sub") if isinstance(payload, dict) else None
@@ -5878,6 +6097,22 @@ def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, b
with CONFIG_LOCK:
previous_config = _load_remote_access_config()
config = api.save_config(payload, generic_remote_access=True)
+ previous_cloud = previous_config.remote_access.vibe_cloud if previous_config is not None else None
+ current_cloud = config.remote_access.vibe_cloud
+ old_instance_id = str(previous_cloud.instance_id or "") if previous_cloud is not None else ""
+ instance_changed = bool(old_instance_id and old_instance_id != str(current_cloud.instance_id or ""))
+ pairing_disabled = bool(
+ previous_cloud is not None
+ and previous_cloud.enabled
+ and not current_cloud.enabled
+ )
+ if instance_changed or pairing_disabled:
+ try:
+ from storage import remote_access_authorization_service
+
+ remote_access_authorization_service.delete_for_instance(old_instance_id)
+ except Exception:
+ logger.warning("Old remote authorization cleanup failed after config save", exc_info=True)
should_reconcile_remote_access = False
if _remote_access_settings_changed(previous_config, config, payload):
if _should_rotate_remote_session_secret(previous_config, config, payload):
@@ -6150,12 +6385,7 @@ def remote_access_optimize_route():
def _cloud_management_subject(config: V2Config | None) -> str | None:
payload = getattr(g, "remote_session_payload", None)
if payload is None and config is not None and _is_remote_access_request(config):
- from vibe import remote_access
-
- payload = remote_access.parse_session_cookie(
- config,
- request.cookies.get(remote_access.SESSION_COOKIE_NAME),
- )
+ payload = _resolved_remote_session_payload(config)
subject = payload.get("sub") if isinstance(payload, Mapping) else None
return subject if isinstance(subject, str) and subject else None
@@ -6673,8 +6903,23 @@ def remote_access_login():
return jsonify({"error": "remote_access_session_secret_missing"}), 503
next_target = _safe_remote_redirect_target(request.args.get("next"))
- session = remote_access.parse_session_cookie(config, request.cookies.get(remote_access.SESSION_COOKIE_NAME))
- if session is not None:
+ identity = remote_access.parse_session_identity(
+ config,
+ request.cookies.get(remote_access.SESSION_COOKIE_NAME),
+ )
+ if identity is not None:
+ resolution = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ refresh_revoked=True,
+ )
+ if resolution.state == "revoked":
+ return jsonify({"error": "remote_access_revoked"}), 403
+ if resolution.state == "unavailable":
+ return jsonify({"error": "remote_access_authorization_unavailable"}), 503
+ else:
+ resolution = None
+ if resolution is not None and resolution.current:
return redirect(next_target)
if _auth_rate_limited():
return _auth_rate_limit_response()
@@ -6773,7 +7018,6 @@ def remote_access_auth_callback():
if claims.get("nonce") != handshake_nonce:
return _oauth_callback_error_response("invalid_oauth_nonce", next_target=next_target)
try:
- remote_access.sync_authorization_revision_once(config)
session_cookie = remote_access.make_session_cookie(
config,
str(claims.get("email", "")),
@@ -6822,32 +7066,56 @@ def api_session():
}
)
else:
- payload = remote_access.parse_session_cookie(
- config, request.cookies.get(remote_access.SESSION_COOKIE_NAME)
+ identity = remote_access.parse_session_identity(
+ config,
+ request.cookies.get(remote_access.SESSION_COOKIE_NAME),
)
- if payload is None:
+ if identity is None:
response = jsonify({"remote": True, "authenticated": False})
- elif remote_access.session_needs_authorization_refresh(payload):
- response = jsonify(
- {
- "remote": True,
- "authenticated": False,
- "authorization_refresh_required": True,
- }
- )
else:
- context = context_from_session_payload(payload)
- response = jsonify(
- {
- "remote": True,
- "authenticated": True,
- "email": str(payload.get("email", "")),
- "sub": str(payload.get("sub", "")),
- "instance_kind": instance_kind,
- "instance_role": context.instance_role,
- "capabilities": context.capability_projection(),
- }
- )
+ resolution = remote_access.resolve_current_authorization(config, identity)
+ if resolution.policy in {"personal", "organization"}:
+ instance_kind = resolution.policy
+ if resolution.state == "unavailable":
+ response = jsonify(
+ {
+ "remote": True,
+ "authenticated": True,
+ "email": str(identity.get("email", "")),
+ "sub": str(identity.get("sub", "")),
+ "instance_kind": instance_kind,
+ "authorization_state": "unavailable",
+ }
+ )
+ elif resolution.state == "revoked":
+ response = jsonify(
+ {
+ "remote": True,
+ "authenticated": True,
+ "email": str(identity.get("email", "")),
+ "sub": str(identity.get("sub", "")),
+ "instance_kind": instance_kind,
+ "authorization_state": "revoked",
+ }
+ )
+ elif not resolution.current:
+ response = jsonify({"remote": True, "authenticated": False})
+ else:
+ payload = resolution.payload
+ context = context_from_session_payload(payload)
+ response = jsonify(
+ {
+ "remote": True,
+ "authenticated": True,
+ "email": str(payload.get("email", "")),
+ "sub": str(payload.get("sub", "")),
+ "instance_kind": instance_kind,
+ "instance_role": context.instance_role,
+ "capabilities": context.capability_projection(),
+ "authorization_state": "current",
+ "authorization_policy": resolution.policy,
+ }
+ )
# Identity payload must never be cached by intermediaries (Cloudflare etc.).
response.headers["Cache-Control"] = "no-store, private"
response.headers["Vary"] = "Cookie"
@@ -6867,10 +7135,7 @@ def _remote_resource_access_context():
or not _is_remote_access_request(config)
):
return None, None, None
- payload = remote_access.parse_session_cookie(
- config,
- request.cookies.get(remote_access.SESSION_COOKIE_NAME),
- )
+ payload = _resolved_remote_session_payload(config)
if payload is None:
return config, None, None
return config, payload, resource_access_service.current_resource_context(
@@ -7119,11 +7384,20 @@ def api_cloud_token():
if config is None:
return jsonify({"error": "cloud_unavailable"}), 503
cookie_value = request.cookies.get(remote_access.SESSION_COOKIE_NAME)
- payload = remote_access.parse_session_cookie(config, cookie_value)
- if payload is not None and remote_access.session_needs_authorization_refresh(payload):
- return jsonify({"ok": False, "error": "remote_access_authorization_refresh_required"}), 401
- result = remote_access.cloud_token_for_request(
- config, cookie_value
+ identity = remote_access.parse_session_identity(config, cookie_value)
+ if identity is None:
+ return jsonify({"ok": False, "error": "remote_access_login_required"}), 401
+ resolution = remote_access.resolve_current_authorization(config, identity)
+ if resolution.state == "revoked":
+ return jsonify({"ok": False, "error": "remote_access_revoked"}), 403
+ if resolution.state == "unavailable":
+ return jsonify(
+ {"ok": False, "error": "remote_access_authorization_unavailable"}
+ ), 503
+ result = (
+ remote_access.cloud_token_for_authorization(config, resolution.payload)
+ if resolution.current
+ else None
)
if result is None:
return jsonify({"error": "cloud_unavailable"}), 503
@@ -7138,6 +7412,33 @@ def api_cloud_token():
def remote_access_logout():
from vibe import remote_access
+ config = _load_remote_access_config()
+ identity = (
+ remote_access.parse_session_identity(
+ config,
+ request.cookies.get(remote_access.SESSION_COOKIE_NAME),
+ )
+ if config is not None
+ else None
+ )
+ if identity is not None:
+ remote_access.revoke_browser_session(identity)
+ body = request.json if isinstance(request.json, dict) else {}
+ device_id = body.get("device_id")
+ endpoint = body.get("endpoint")
+ try:
+ from storage import web_push_service
+
+ engine = _projects_engine()
+ with engine.begin() as conn:
+ web_push_service.disable_device_subscription(
+ conn,
+ user_key=f"remote:{identity['sub']}",
+ device_id=device_id if isinstance(device_id, str) else None,
+ endpoint=endpoint if isinstance(endpoint, str) else None,
+ )
+ except Exception:
+ logger.warning("remote logout could not disable browser Push", exc_info=True)
# Suppress the after-request renewal so we don't re-issue the cookie we're
# about to clear; flagged so future hook reorderings stay safe.
g.remote_session_renew = None
@@ -11709,26 +12010,36 @@ async def workbench_events():
from vibe.sse_broker import broker
authorization_context = getattr(g, "authorization_context", None)
- authorization_refresh_at = getattr(g, "remote_authorization_refresh_at", None)
+ remote_session_identity = getattr(g, "remote_session_identity", None)
remote_session_payload = getattr(g, "remote_session_payload", None)
remote_config = _load_remote_access_config() if remote_session_payload is not None else None
-
- def authorization_is_current() -> bool:
- if remote_session_payload is None:
- return True
- if remote_config is None:
- return False
+ remote_session_cookie = None
+ remote_request_host = None
+ if remote_session_payload is not None:
from vibe import remote_access
- return remote_access.session_authorization_is_current(
+ remote_session_cookie = request.cookies.get(remote_access.SESSION_COOKIE_NAME)
+ remote_request_host = _effective_normalized_host()
+
+ async def authorization_state() -> str:
+ if remote_session_payload is None:
+ return "current"
+ if remote_config is None or remote_session_identity is None:
+ return "invalid_identity"
+ return await _remote_stream_authorization_state(
remote_config,
+ remote_session_identity,
remote_session_payload,
+ session_cookie=remote_session_cookie,
+ request_host=remote_request_host,
)
async def generate():
sub_id, queue = broker.subscribe()
try:
- if not authorization_is_current():
+ state = await authorization_state()
+ if state != "current":
+ yield _remote_authorization_sse_frame(state)
return
# First chunk = handshake + sub_id so the client can include it in
# subsequent debug logs / cancel calls if we ever need them.
@@ -11744,17 +12055,15 @@ async def workbench_events():
)
yield f"event: {WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT}\ndata: {payload}\n\n"
while True:
- if not authorization_is_current():
+ state = await authorization_state()
+ if state != "current":
+ yield _remote_authorization_sse_frame(state)
return
- wait_timeout = 15.0
- if authorization_refresh_at is not None:
- remaining = authorization_refresh_at - time.time()
- if remaining <= 0:
- return
- wait_timeout = min(wait_timeout, remaining)
try:
- event_type, payload = await asyncio.wait_for(queue.get(), timeout=wait_timeout)
- if not authorization_is_current():
+ event_type, payload = await asyncio.wait_for(queue.get(), timeout=15.0)
+ state = await authorization_state()
+ if state != "current":
+ yield _remote_authorization_sse_frame(state)
return
if not can_receive_workbench_event(authorization_context, event_type):
continue
@@ -11788,9 +12097,9 @@ async def workbench_events():
)
yield f"event: {event_type}\ndata: {payload}\n\n"
except asyncio.TimeoutError:
- if not authorization_is_current():
- return
- if authorization_refresh_at is not None and time.time() >= authorization_refresh_at:
+ state = await authorization_state()
+ if state != "current":
+ yield _remote_authorization_sse_frame(state)
return
# 15s keep-alive — Cloudflare Tunnel default idle is well
# below 100s but this still keeps mid-tier proxies happy.
@@ -12877,13 +13186,10 @@ def _show_request_author(*, public: bool = False) -> dict[str, str] | None:
config = _load_remote_access_config()
if config is not None:
- session = remote_access.parse_session_cookie(
- config,
- request.cookies.get(remote_access.SESSION_COOKIE_NAME),
- )
+ session = _resolved_remote_session_payload(config)
context = (
context_from_session_payload(session)
- if session is not None and not remote_access.session_needs_authorization_refresh(session)
+ if session is not None
else None
)
if context is not None:
@@ -13443,7 +13749,10 @@ async def _show_events_stream(
remote: bool = False,
authorization_refresh_at: float | None = None,
authorization_context: Any = None,
+ remote_session_identity: Mapping[str, Any] | None = None,
remote_session_payload: Mapping[str, Any] | None = None,
+ remote_session_cookie: str | None = None,
+ remote_request_host: str | None = None,
remote_config: V2Config | None = None,
):
import asyncio
@@ -13455,16 +13764,18 @@ async def _show_events_stream(
def _event_visible(event_payload: dict[str, Any]) -> bool:
return event_payload.get("session_id") == session_id
- def _authorization_is_current() -> bool:
+ async def _authorization_state() -> str:
if remote_session_payload is None:
- return True
+ return "current"
+ identity = remote_session_identity or remote_session_payload
if remote_config is None:
- return False
- from vibe import remote_access
-
- return remote_access.session_authorization_is_current(
+ return "invalid_identity"
+ return await _remote_stream_authorization_state(
remote_config,
+ identity,
remote_session_payload,
+ session_cookie=remote_session_cookie,
+ request_host=remote_request_host,
)
async def generate():
@@ -13474,7 +13785,9 @@ async def _show_events_stream(
store = _show_session_event_store()
try:
cursor = after_id
- if not _authorization_is_current():
+ state = await _authorization_state()
+ if state != "current":
+ yield _remote_authorization_sse_frame(state)
return
yield ": show events connected\n\n"
if not public and (
@@ -13488,21 +13801,19 @@ async def _show_events_stream(
session_id,
)
):
+ if remote_session_payload is not None:
+ yield _remote_authorization_sse_frame("revoked")
return
while True:
- if not _authorization_is_current():
- return
- if authorization_refresh_at is not None and time.time() >= authorization_refresh_at:
+ state = await _authorization_state()
+ if state != "current":
+ yield _remote_authorization_sse_frame(state)
return
batch = store.list(session_id, after_id=cursor, limit=500)
events = batch["events"]
if not events:
break
for event_payload in events:
- if not _authorization_is_current():
- return
- if authorization_refresh_at is not None and time.time() >= authorization_refresh_at:
- return
if isinstance(event_payload.get("id"), str):
replayed_ids.add(event_payload["id"])
yield _sse_frame(
@@ -13521,17 +13832,15 @@ async def _show_events_stream(
store.close()
while True:
- if not _authorization_is_current():
+ state = await _authorization_state()
+ if state != "current":
+ yield _remote_authorization_sse_frame(state)
return
- wait_timeout = 15.0
- if authorization_refresh_at is not None:
- remaining = authorization_refresh_at - time.time()
- if remaining <= 0:
- return
- wait_timeout = min(wait_timeout, remaining)
try:
- event_type, payload = await asyncio.wait_for(queue.get(), timeout=wait_timeout)
- if not _authorization_is_current():
+ event_type, payload = await asyncio.wait_for(queue.get(), timeout=15.0)
+ state = await _authorization_state()
+ if state != "current":
+ yield _remote_authorization_sse_frame(state)
return
decoded = json.loads(payload)
event_payload = decoded.get("data") if isinstance(decoded, dict) else None
@@ -13544,6 +13853,8 @@ async def _show_events_stream(
authorization_context,
session_id,
):
+ if remote_session_payload is not None:
+ yield _remote_authorization_sse_frame("revoked")
return
elif event_type == "show.event" and isinstance(event_payload, dict) and _event_visible(event_payload):
event_id = event_payload.get("id")
@@ -13573,9 +13884,9 @@ async def _show_events_stream(
),
)
except asyncio.TimeoutError:
- if not _authorization_is_current():
- return
- if authorization_refresh_at is not None and time.time() >= authorization_refresh_at:
+ state = await _authorization_state()
+ if state != "current":
+ yield _remote_authorization_sse_frame(state)
return
yield ": ping\n\n"
except asyncio.CancelledError:
@@ -13604,6 +13915,14 @@ async def _show_events_response(
# Resolve the projection before the SSE generator loses request context.
authorization_context = None if public else getattr(g, "authorization_context", None)
remote = not public and _is_remote_show_page_request()
+ remote_session_payload = None if public else getattr(g, "remote_session_payload", None)
+ remote_session_cookie = None
+ remote_request_host = None
+ if remote_session_payload is not None:
+ from vibe import remote_access
+
+ remote_session_cookie = request.cookies.get(remote_access.SESSION_COOKIE_NAME)
+ remote_request_host = _effective_normalized_host()
if request.method == "GET":
if request.args.get("stream") == "1":
return await _show_events_stream(
@@ -13612,16 +13931,16 @@ async def _show_events_response(
public=public,
public_share_id=public_share_id,
remote=remote,
- authorization_refresh_at=(
- None if public else getattr(g, "remote_authorization_refresh_at", None)
- ),
authorization_context=authorization_context,
- remote_session_payload=(
- None if public else getattr(g, "remote_session_payload", None)
+ remote_session_identity=(
+ None if public else getattr(g, "remote_session_identity", None)
),
+ remote_session_payload=remote_session_payload,
+ remote_session_cookie=remote_session_cookie,
+ remote_request_host=remote_request_host,
remote_config=(
None
- if public or getattr(g, "remote_session_payload", None) is None
+ if remote_session_payload is None
else _load_remote_access_config()
),
)