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(ui): harden web push delivery

cyh5e82ebeae123
diff --git a/core/web_push.py b/core/web_push.py
index 6620307b3..a26f5c212 100644
--- a/core/web_push.py
+++ b/core/web_push.py
@@ -17,6 +17,7 @@ from config import paths
logger = logging.getLogger(__name__)
_VAPID_FILE = "web_push_vapid.json"
+DEFAULT_WEB_PUSH_TIMEOUT_SECONDS = 10.0
@dataclass(frozen=True)
@@ -82,6 +83,7 @@ def send_web_push(
payload: dict[str, Any],
vapid_keys: VapidKeys | None = None,
subject: str = "mailto:[email protected]",
+ timeout: float = DEFAULT_WEB_PUSH_TIMEOUT_SECONDS,
) -> None:
"""Send one Web Push payload.
@@ -89,9 +91,11 @@ def send_web_push(
generation or subscription APIs do not need network-capable setup.
"""
+ from py_vapid import Vapid
from pywebpush import webpush
keys = vapid_keys or load_or_create_vapid_keys()
+ vapid_signer = Vapid.from_pem(keys.private_key_pem.encode("ascii"))
subscription_info = {
"endpoint": subscription["endpoint"],
"keys": {
@@ -102,6 +106,7 @@ def send_web_push(
webpush(
subscription_info=subscription_info,
data=json.dumps(payload, separators=(",", ":")),
- vapid_private_key=keys.private_key_pem,
+ vapid_private_key=vapid_signer,
vapid_claims={"sub": subject},
+ timeout=timeout,
)
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index ec795b966..92e06b5ce 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -14,7 +14,6 @@ from storage.models import agent_sessions
logger = logging.getLogger(__name__)
_NOTIFIABLE_TYPES = {"result", "notify", "error"}
-_LOCAL_USER_KEY = "local"
def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[str, Any] | None) -> None:
@@ -49,22 +48,22 @@ def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[s
thread.start()
-def _user_key_for_session(conn: Any, session_id: str | None) -> str:
+def _user_key_for_session(conn: Any, session_id: str | None) -> str | None:
if not session_id:
- return _LOCAL_USER_KEY
+ return None
row = conn.execute(
select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)
).first()
if row is None:
- return _LOCAL_USER_KEY
+ return None
try:
import json
metadata = json.loads(row[0] or "{}")
except Exception:
- return _LOCAL_USER_KEY
+ return None
user_key = metadata.get("_web_push_user_key") if isinstance(metadata, dict) else None
- return user_key if isinstance(user_key, str) and user_key.strip() else _LOCAL_USER_KEY
+ return user_key if isinstance(user_key, str) and user_key.strip() else None
def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:
@@ -73,17 +72,22 @@ def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:
engine = create_sqlite_engine()
try:
- with engine.begin() as conn:
+ with engine.connect() as conn:
user_key = _user_key_for_session(conn, payload.get("session_id"))
+ if user_key is None:
+ logger.debug("web push: skip notification for session without push owner")
+ return
subscriptions = web_push_service.list_enabled(conn, user_key=user_key)
- for subscription in subscriptions:
- try:
- send_web_push(subscription=subscription, payload=payload)
+ for subscription in subscriptions:
+ try:
+ send_web_push(subscription=subscription, payload=payload)
+ with engine.begin() as conn:
web_push_service.mark_send_success(conn, endpoint=subscription["endpoint"])
- except Exception as exc:
- status_code = getattr(getattr(exc, "response", None), "status_code", None)
- disable = status_code in {404, 410}
- logger.warning("web push: send failed", exc_info=True)
+ except Exception as exc:
+ status_code = getattr(getattr(exc, "response", None), "status_code", None)
+ disable = status_code in {404, 410}
+ logger.warning("web push: send failed", exc_info=True)
+ with engine.begin() as conn:
web_push_service.mark_send_failure(
conn,
endpoint=subscription["endpoint"],
diff --git a/storage/web_push_service.py b/storage/web_push_service.py
index a5f7a27a4..7e7473c7a 100644
--- a/storage/web_push_service.py
+++ b/storage/web_push_service.py
@@ -90,15 +90,16 @@ def upsert_subscription(
return _row_to_dict(row)
-def disable_subscription(conn: Connection, *, endpoint: str) -> bool:
+def disable_subscription(conn: Connection, *, endpoint: str, user_key: str | None = None) -> bool:
endpoint = endpoint.strip() if isinstance(endpoint, str) else ""
if not endpoint:
return False
now = _utc_now_iso()
+ stmt = web_push_subscriptions.update().where(web_push_subscriptions.c.endpoint == endpoint)
+ if user_key is not None:
+ stmt = stmt.where(web_push_subscriptions.c.user_key == user_key)
result = conn.execute(
- web_push_subscriptions.update()
- .where(web_push_subscriptions.c.endpoint == endpoint)
- .values(enabled=0, updated_at=now)
+ stmt.values(enabled=0, updated_at=now)
)
return bool(result.rowcount)
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 1787ed681..7f2931964 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -179,6 +179,42 @@ def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):
assert status_after.get_json()["subscription_count"] == 0
+def test_web_push_unsubscribe_is_scoped_to_current_user(monkeypatch, tmp_path):
+ from storage import web_push_service
+ from storage.db import create_sqlite_engine
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ monkeypatch.setattr(ui_server, "_web_push_user_key", lambda: "remote:user-a")
+
+ endpoint = "https://push.example.test/sub/other"
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-b",
+ payload={
+ "endpoint": endpoint,
+ "keys": {
+ "p256dh": "p256dh-key",
+ "auth": "auth-secret",
+ },
+ },
+ )
+
+ client = app.test_client()
+ removed = client.delete(
+ "/api/web-push/subscriptions",
+ json={"endpoint": endpoint},
+ headers=csrf_headers(client),
+ )
+
+ assert removed.status_code == 200
+ assert removed.get_json() == {"ok": True, "disabled": False}
+ with engine.connect() as conn:
+ assert web_push_service.count_enabled(conn, user_key="remote:user-b") == 1
+
+
def test_web_push_test_route_sends_to_enabled_subscriptions(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
ensure_sqlite_state()
diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.py
index d08232511..fb892b9b0 100644
--- a/tests/test_web_push_notifications.py
+++ b/tests/test_web_push_notifications.py
@@ -126,3 +126,48 @@ def test_send_to_enabled_subscriptions_uses_session_owner(monkeypatch, tmp_path)
)
assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/a"]
+
+
+def test_send_to_enabled_subscriptions_skips_unknown_owner(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-06-04T00:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_x", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_legacy",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="ses_legacy",
+ native_session_id="",
+ title="Legacy",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="local",
+ payload={
+ "endpoint": "https://push.example.test/local",
+ "keys": {"p256dh": "local-key", "auth": "local-auth"},
+ },
+ )
+
+ sends = []
+ monkeypatch.setattr(
+ "core.web_push.send_web_push",
+ lambda *, subscription, payload: sends.append((subscription, payload)),
+ )
+
+ web_push_notifications._send_to_enabled_subscriptions(
+ {"title": "Legacy", "body": "Done", "session_id": "ses_legacy"}
+ )
+
+ assert sends == []
diff --git a/tests/test_web_push_service.py b/tests/test_web_push_service.py
index 2bc3f2b4c..aa9d64ef1 100644
--- a/tests/test_web_push_service.py
+++ b/tests/test_web_push_service.py
@@ -4,7 +4,7 @@ import json
import pytest
-from core.web_push import load_or_create_vapid_keys
+from core.web_push import DEFAULT_WEB_PUSH_TIMEOUT_SECONDS, load_or_create_vapid_keys, send_web_push
from storage import web_push_service
from storage.db import create_sqlite_engine
from storage.migrations import run_migrations
@@ -36,7 +36,14 @@ def test_subscription_upsert_and_disable(tmp_path):
assert updated["user_agent"] == "ua2"
assert web_push_service.count_enabled(conn, user_key="local") == 1
- assert web_push_service.disable_subscription(conn, endpoint=_payload()["endpoint"]) is True
+ assert web_push_service.disable_subscription(
+ conn,
+ endpoint=_payload()["endpoint"],
+ user_key="someone-else",
+ ) is False
+ assert web_push_service.count_enabled(conn, user_key="local") == 1
+
+ assert web_push_service.disable_subscription(conn, endpoint=_payload()["endpoint"], user_key="local") is True
assert web_push_service.count_enabled(conn, user_key="local") == 0
@@ -65,3 +72,28 @@ def test_vapid_keys_are_stable(tmp_path):
assert "PRIVATE KEY" in first.private_key_pem
stored = json.loads(key_path.read_text(encoding="utf-8"))
assert stored["public_key"] == first.public_key
+
+
+def test_send_web_push_passes_vapid_signer_and_timeout(monkeypatch, tmp_path):
+ keys = load_or_create_vapid_keys(tmp_path / "web_push_vapid.json")
+ calls = []
+
+ def fake_webpush(**kwargs):
+ calls.append(kwargs)
+
+ monkeypatch.setattr("pywebpush.webpush", fake_webpush)
+
+ send_web_push(
+ subscription={
+ "endpoint": "https://push.example.test/sub/1",
+ "p256dh": "p256dh-key",
+ "auth": "auth-secret",
+ },
+ payload={"title": "Hello"},
+ vapid_keys=keys,
+ )
+
+ assert len(calls) == 1
+ assert calls[0]["timeout"] == DEFAULT_WEB_PUSH_TIMEOUT_SECONDS
+ assert not isinstance(calls[0]["vapid_private_key"], str)
+ assert calls[0]["subscription_info"]["endpoint"] == "https://push.example.test/sub/1"
diff --git a/ui/src/lib/webPush.ts b/ui/src/lib/webPush.ts
index c7be35c01..3c4068fb1 100644
--- a/ui/src/lib/webPush.ts
+++ b/ui/src/lib/webPush.ts
@@ -14,6 +14,16 @@ function urlBase64ToArrayBuffer(value: string): ArrayBuffer {
return output.buffer;
}
+function arrayBuffersEqual(left: ArrayBuffer | null, right: ArrayBuffer): boolean {
+ if (!left || left.byteLength !== right.byteLength) return false;
+ const leftView = new Uint8Array(left);
+ const rightView = new Uint8Array(right);
+ for (let i = 0; i < leftView.length; i += 1) {
+ if (leftView[i] !== rightView[i]) return false;
+ }
+ return true;
+}
+
export function getWebPushSupportState(): WebPushSupportState {
if (typeof window === 'undefined' || typeof navigator === 'undefined') {
return { supported: false, reason: 'unsupported' };
@@ -44,12 +54,17 @@ export async function enableWebPush(api: ApiContextType): Promise<PushSubscripti
}
const registration = await navigator.serviceWorker.register('/push-sw.js');
+ const serverKey = urlBase64ToArrayBuffer((await api.getWebPushVapidPublicKey()).public_key);
const existing = await registration.pushManager.getSubscription();
+ if (existing && !arrayBuffersEqual(existing.options.applicationServerKey, serverKey)) {
+ await existing.unsubscribe();
+ }
+ const current = await registration.pushManager.getSubscription();
const subscription =
- existing ??
+ current ??
(await registration.pushManager.subscribe({
userVisibleOnly: true,
- applicationServerKey: urlBase64ToArrayBuffer((await api.getWebPushVapidPublicKey()).public_key),
+ applicationServerKey: serverKey,
}));
const json = subscription.toJSON();
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 81cc0de8c..d3e07d542 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1863,7 +1863,11 @@ def web_push_unsubscribe():
return jsonify({"ok": False, "error": "endpoint_required"}), 400
engine = _projects_engine()
with engine.begin() as conn:
- disabled = web_push_service.disable_subscription(conn, endpoint=endpoint)
+ disabled = web_push_service.disable_subscription(
+ conn,
+ endpoint=endpoint,
+ user_key=_web_push_user_key(),
+ )
return jsonify({"ok": True, "disabled": disabled})
@@ -1883,24 +1887,26 @@ def web_push_test():
engine = _projects_engine()
sent = 0
failed = 0
- with engine.begin() as conn:
+ with engine.connect() as conn:
subscriptions = web_push_service.list_enabled(conn, user_key=user_key)
- if not subscriptions:
- return jsonify({"ok": False, "error": "no_subscription"}), 404
- for subscription in subscriptions:
- try:
- send_web_push(subscription=subscription, payload=notification)
+ if not subscriptions:
+ return jsonify({"ok": False, "error": "no_subscription"}), 404
+ for subscription in subscriptions:
+ try:
+ send_web_push(subscription=subscription, payload=notification)
+ with engine.begin() as conn:
web_push_service.mark_send_success(conn, endpoint=subscription["endpoint"])
- sent += 1
- except Exception as exc:
- logger.warning("web push: test send failed", exc_info=True)
- status_code = getattr(getattr(exc, "response", None), "status_code", None)
+ sent += 1
+ except Exception as exc:
+ logger.warning("web push: test send failed", exc_info=True)
+ status_code = getattr(getattr(exc, "response", None), "status_code", None)
+ with engine.begin() as conn:
web_push_service.mark_send_failure(
conn,
endpoint=subscription["endpoint"],
disable=status_code in {404, 410},
)
- failed += 1
+ failed += 1
return jsonify({"ok": failed == 0, "sent": sent, "failed": failed})