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): recover rotated web push subscriptions (#2150)

Call White2253b3bd9e37
diff --git a/storage/alembic/versions/20260923_0062_web_push_provider_invalidation.py b/storage/alembic/versions/20260923_0062_web_push_provider_invalidation.py
new file mode 100644
index 000000000..e0eddc5e9
--- /dev/null
+++ b/storage/alembic/versions/20260923_0062_web_push_provider_invalidation.py
@@ -0,0 +1,44 @@
+"""Distinguish confirmed Web Push provider invalidation from legacy failures.
+
+Revision ID: 20260923_0062
+Revises: 20260907_0061
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260923_0062"
+down_revision = "20260907_0061"
+branch_labels = None
+depends_on = None
+MIGRATION_SAFETY = "additive"
+
+
+def _columns() -> set[str]:
+ return {
+ row[1]
+ for row in op.get_bind().exec_driver_sql('pragma table_info("web_push_subscriptions")')
+ }
+
+
+def upgrade() -> None:
+ # Older releases used last_failure_at for both transient failures and
+ # disabled endpoints. Their disabled rows have no trustworthy provenance;
+ # leave them opted out until the user explicitly enables notifications.
+ if "provider_invalidated_at" not in _columns():
+ op.add_column(
+ "web_push_subscriptions",
+ sa.Column("provider_invalidated_at", sa.String(), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ if "provider_invalidated_at" in _columns():
+ # Older SQLite cannot drop a column without rebuilding the table.
+ # Keep the harmless additive column, but revoke repair eligibility:
+ # older code cannot clear this marker on an explicit opt-out.
+ op.get_bind().exec_driver_sql(
+ 'update "web_push_subscriptions" set "provider_invalidated_at" = null'
+ )
diff --git a/storage/migrations.py b/storage/migrations.py
index 2e6000450..e55cc5c3c 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -159,7 +159,7 @@ HEAD_ONLY_REQUIRED_COLUMNS = {
"organization_id",
"created_at",
},
- "web_push_subscriptions": {"device_id"},
+ "web_push_subscriptions": {"device_id", "provider_invalidated_at"},
"remote_access_authorizations": {
"instance_id",
"subject",
@@ -674,6 +674,9 @@ def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) ->
if "web_push_subscriptions" in tables and "device_id" not in _column_names(conn, "web_push_subscriptions"):
conn.execute('alter table "web_push_subscriptions" add column "device_id" VARCHAR')
changed = True
+ if "web_push_subscriptions" in tables and "provider_invalidated_at" not in _column_names(conn, "web_push_subscriptions"):
+ conn.execute('alter table "web_push_subscriptions" add column "provider_invalidated_at" VARCHAR')
+ changed = True
_ensure_head_indexes(conn, tables)
return changed
diff --git a/storage/models.py b/storage/models.py
index fdce0cc5f..7150d1106 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -1141,6 +1141,7 @@ web_push_subscriptions = Table(
Column("enabled", Integer, nullable=False),
Column("last_success_at", String, nullable=True),
Column("last_failure_at", String, nullable=True),
+ Column("provider_invalidated_at", String, nullable=True),
Column("failure_count", Integer, nullable=False),
Column("created_at", String, nullable=False),
Column("updated_at", String, nullable=False),
diff --git a/storage/web_push_service.py b/storage/web_push_service.py
index d35f0c723..8f22f3ff0 100644
--- a/storage/web_push_service.py
+++ b/storage/web_push_service.py
@@ -74,12 +74,12 @@ def _disable_previous_endpoints(
endpoints = _normalize_previous_endpoints(previous_endpoints, endpoint)
if not endpoints:
return
+ # A replaced endpoint can no longer authorize another automatic repair.
conn.execute(
web_push_subscriptions.update()
.where(web_push_subscriptions.c.user_key == user_key)
.where(web_push_subscriptions.c.endpoint.in_(endpoints))
- .where(web_push_subscriptions.c.enabled == 1)
- .values(enabled=0, updated_at=now)
+ .values(enabled=0, provider_invalidated_at=None, updated_at=now)
)
@@ -111,8 +111,7 @@ def upsert_subscription(
.where(web_push_subscriptions.c.user_key == user_key)
.where(web_push_subscriptions.c.device_id == device_id)
.where(web_push_subscriptions.c.endpoint != endpoint)
- .where(web_push_subscriptions.c.enabled == 1)
- .values(enabled=0, updated_at=now)
+ .values(enabled=0, provider_invalidated_at=None, updated_at=now)
)
stmt = sqlite_insert(web_push_subscriptions).values(
id=_new_id(),
@@ -138,6 +137,8 @@ def upsert_subscription(
"user_agent": user_agent,
"device_label": device_label,
"enabled": 1,
+ "last_failure_at": None,
+ "provider_invalidated_at": None,
"failure_count": 0,
"updated_at": now,
},
@@ -149,6 +150,50 @@ def upsert_subscription(
return _row_to_dict(row)
+def upsert_background_rotated_subscription(
+ conn: Connection,
+ *,
+ user_key: str,
+ payload: dict[str, Any],
+ previous_endpoints: list[str] | None = None,
+ user_agent: str | None = None,
+) -> dict[str, Any] | None:
+ """Accept a service-worker rotation only for an active or provider-failed row."""
+
+ endpoint, _, _ = validate_subscription_payload(payload)
+ previous_candidates = _normalize_previous_endpoints(previous_endpoints, endpoint)
+ if not previous_candidates:
+ return None
+ previous = conn.execute(
+ select(web_push_subscriptions)
+ .where(web_push_subscriptions.c.user_key == user_key)
+ .where(web_push_subscriptions.c.endpoint.in_(previous_candidates))
+ .where(
+ (web_push_subscriptions.c.enabled == 1)
+ | web_push_subscriptions.c.provider_invalidated_at.is_not(None)
+ )
+ .limit(1)
+ ).mappings().first()
+ if previous is None:
+ return None
+
+ current = get_by_endpoint(conn, endpoint=endpoint, user_key=user_key)
+ if current is not None and not current["enabled"] and not current.get("provider_invalidated_at"):
+ return None
+ return upsert_subscription(
+ conn,
+ user_key=user_key,
+ payload=payload,
+ user_agent=user_agent,
+ device_id=(
+ current.get("device_id")
+ if current is not None
+ else previous.get("device_id")
+ ),
+ previous_endpoints=previous_endpoints,
+ )
+
+
def attach_device_to_enabled_subscription(
conn: Connection,
*,
@@ -164,6 +209,40 @@ def attach_device_to_enabled_subscription(
if not device_id:
return get_enabled_by_endpoint(conn, endpoint=endpoint, user_key=user_key)
now = _utc_now_iso()
+ previous_candidates = _normalize_previous_endpoints(previous_endpoints, endpoint)
+ recoverable_previous = None
+ if previous_candidates:
+ previous_rows = conn.execute(
+ select(web_push_subscriptions)
+ .where(web_push_subscriptions.c.user_key == user_key)
+ .where(web_push_subscriptions.c.endpoint.in_(previous_candidates))
+ .where(
+ (web_push_subscriptions.c.enabled == 1)
+ | web_push_subscriptions.c.provider_invalidated_at.is_not(None)
+ )
+ ).mappings().all()
+ for previous_row in previous_rows:
+ previous_device_id = previous_row["device_id"]
+ if previous_device_id is not None and previous_device_id != device_id:
+ continue
+ recoverable_previous = previous_row
+ break
+ existing = get_enabled_by_endpoint(conn, endpoint=endpoint, user_key=user_key)
+ if existing is None:
+ if (
+ get_by_endpoint(conn, endpoint=endpoint, user_key=user_key) is None
+ and recoverable_previous is not None
+ ):
+ return upsert_subscription(
+ conn,
+ user_key=user_key,
+ payload=payload,
+ user_agent=user_agent,
+ device_label=device_label,
+ device_id=device_id,
+ previous_endpoints=previous_endpoints,
+ )
+ return None
_disable_previous_endpoints(
conn,
user_key=user_key,
@@ -171,16 +250,12 @@ def attach_device_to_enabled_subscription(
previous_endpoints=previous_endpoints,
now=now,
)
- existing = get_enabled_by_endpoint(conn, endpoint=endpoint, user_key=user_key)
- if existing is None:
- return None
conn.execute(
web_push_subscriptions.update()
.where(web_push_subscriptions.c.user_key == user_key)
.where(web_push_subscriptions.c.device_id == device_id)
.where(web_push_subscriptions.c.endpoint != endpoint)
- .where(web_push_subscriptions.c.enabled == 1)
- .values(enabled=0, updated_at=now)
+ .values(enabled=0, provider_invalidated_at=None, updated_at=now)
)
values = {
"p256dh": p256dh,
@@ -210,7 +285,7 @@ def disable_subscription(conn: Connection, *, endpoint: str, user_key: str | Non
if user_key is not None:
stmt = stmt.where(web_push_subscriptions.c.user_key == user_key)
result = conn.execute(
- stmt.values(enabled=0, updated_at=now)
+ stmt.values(enabled=0, last_failure_at=None, provider_invalidated_at=None, updated_at=now)
)
return bool(result.rowcount)
@@ -222,23 +297,34 @@ def disable_device_subscription(
device_id: str | None = None,
endpoint: str | None = None,
) -> bool:
- """Disable only the logging-out browser's selected Push subscription."""
+ """Disable the submitted endpoint and any rotated row for this browser."""
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
+ device_ids = {device_id} if device_id else set()
+ if endpoint:
+ endpoint_row = get_by_endpoint(conn, endpoint=endpoint, user_key=user_key)
+ if endpoint_row and endpoint_row.get("device_id"):
+ # A previous endpoint keeps the rotation's device identity even if
+ # another tab submitted a different ID during logout.
+ device_ids.add(endpoint_row["device_id"])
stmt = (
web_push_subscriptions.update()
.where(web_push_subscriptions.c.user_key == user_key)
- .where(web_push_subscriptions.c.enabled == 1)
)
- if endpoint:
+ if endpoint and device_ids:
+ stmt = stmt.where(
+ (web_push_subscriptions.c.endpoint == endpoint)
+ | (web_push_subscriptions.c.device_id.in_(device_ids))
+ )
+ elif endpoint:
stmt = stmt.where(web_push_subscriptions.c.endpoint == endpoint)
else:
- stmt = stmt.where(web_push_subscriptions.c.device_id == device_id)
+ stmt = stmt.where(web_push_subscriptions.c.device_id.in_(device_ids))
result = conn.execute(
- stmt.values(enabled=0, updated_at=_utc_now_iso())
+ stmt.values(enabled=0, last_failure_at=None, provider_invalidated_at=None, updated_at=_utc_now_iso())
)
return bool(result.rowcount)
@@ -270,7 +356,7 @@ def has_enabled_user_key(conn: Connection, *, user_key: str) -> bool:
return row is not None
-def get_enabled_by_endpoint(
+def get_by_endpoint(
conn: Connection,
*,
endpoint: str,
@@ -282,7 +368,6 @@ def get_enabled_by_endpoint(
stmt = (
select(web_push_subscriptions)
.where(web_push_subscriptions.c.endpoint == endpoint)
- .where(web_push_subscriptions.c.enabled == 1)
)
if user_key is not None:
stmt = stmt.where(web_push_subscriptions.c.user_key == user_key)
@@ -290,12 +375,23 @@ def get_enabled_by_endpoint(
return _row_to_dict(row) if row else None
+def get_enabled_by_endpoint(
+ conn: Connection,
+ *,
+ endpoint: str,
+ user_key: str | None = None,
+) -> dict[str, Any] | None:
+ row = get_by_endpoint(conn, endpoint=endpoint, user_key=user_key)
+ return row if row and row["enabled"] else None
+
+
def mark_send_success(conn: Connection, *, endpoint: str) -> None:
now = _utc_now_iso()
conn.execute(
web_push_subscriptions.update()
.where(web_push_subscriptions.c.endpoint == endpoint)
- .values(last_success_at=now, last_failure_at=None, failure_count=0, updated_at=now)
+ .where(web_push_subscriptions.c.enabled == 1)
+ .values(last_success_at=now, last_failure_at=None, provider_invalidated_at=None, failure_count=0, updated_at=now)
)
@@ -308,6 +404,10 @@ def mark_send_failure(conn: Connection, *, endpoint: str, disable: bool = False)
}
if disable:
values["enabled"] = 0
+ values["provider_invalidated_at"] = now
conn.execute(
- web_push_subscriptions.update().where(web_push_subscriptions.c.endpoint == endpoint).values(**values)
+ web_push_subscriptions.update()
+ .where(web_push_subscriptions.c.endpoint == endpoint)
+ .where(web_push_subscriptions.c.enabled == 1)
+ .values(**values)
)
diff --git a/tests/test_skill_observability_migration.py b/tests/test_skill_observability_migration.py
index 3634170f3..555d93c0b 100644
--- a/tests/test_skill_observability_migration.py
+++ b/tests/test_skill_observability_migration.py
@@ -32,7 +32,7 @@ def test_skill_schema_upgrade_downgrade_preserves_existing_events(tmp_path):
migrations.run_migrations(path)
with sqlite3.connect(path) as conn:
assert conn.execute("SELECT * FROM agent_events ORDER BY id").fetchall() == original
- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20260907_0061",)
+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20260923_0062",)
assert conn.execute("SELECT count(*) FROM skill_usage_daily").fetchone() == (0,)
assert {row[2] for row in conn.execute("PRAGMA foreign_key_list(skill_usage_daily)")} == {
"scopes",
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 1eec89471..ec3840931 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -37,7 +37,7 @@ from vibe.message_types import build_partial_index_predicate
pytestmark = pytest.mark.no_sqlite_template
-HEAD_REVISION = "20260907_0061"
+HEAD_REVISION = "20260923_0062"
# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and
# Alembic cannot re-emit them when batch mode recreates a table. Every migration that
# rebuilds one therefore passes this convention; the rebuild simulated below has to pass
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index d2de25859..68a97b398 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -3333,6 +3333,7 @@ def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):
assert status_body["public_key"]
assert status_body["subscription_count"] == 1
assert status_body["current_subscription_enabled"] is True
+ assert status_body["current_subscription_repairable"] is False
removed = client.delete(
"/api/web-push/subscriptions",
@@ -3345,6 +3346,60 @@ def test_web_push_subscription_routes_roundtrip(monkeypatch, tmp_path):
status_after = client.post("/api/web-push/status", json={"endpoint": subscription["endpoint"]}, headers=headers)
assert status_after.get_json()["subscription_count"] == 0
assert status_after.get_json()["current_subscription_enabled"] is False
+ assert status_after.get_json()["current_subscription_repairable"] is False
+
+
+def test_web_push_disable_retires_a_racing_rotation_for_same_device(monkeypatch, tmp_path):
+ from storage import web_push_service
+ from storage.db import create_sqlite_engine
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ client = app.test_client()
+ headers = csrf_headers(client)
+ old = {
+ "endpoint": "https://push.example.test/sub/old",
+ "keys": {"p256dh": "old-key", "auth": "old-auth"},
+ }
+ rotated = {
+ "endpoint": "https://push.example.test/sub/rotated",
+ "keys": {"p256dh": "new-key", "auth": "new-auth"},
+ }
+ other = {
+ "endpoint": "https://push.example.test/sub/other",
+ "keys": {"p256dh": "other-key", "auth": "other-auth"},
+ }
+ assert client.post(
+ "/api/web-push/subscriptions",
+ json={"subscription": old, "device_id": "device-1"},
+ headers=headers,
+ ).status_code == 200
+ assert client.post(
+ "/api/web-push/subscriptions",
+ json={"subscription": rotated, "background_rotation": True, "previous_endpoints": [old["endpoint"]]},
+ headers=headers,
+ ).get_json()["accepted"] is True
+ assert client.post(
+ "/api/web-push/subscriptions",
+ json={"subscription": other, "device_id": "device-2"},
+ headers=headers,
+ ).status_code == 200
+
+ disabled = client.delete(
+ "/api/web-push/subscriptions",
+ json={"endpoint": old["endpoint"], "device_id": "device-1"},
+ headers=headers,
+ )
+ assert disabled.status_code == 200
+ assert disabled.get_json()["disabled"] is True
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ assert web_push_service.get_enabled_by_endpoint(
+ conn, endpoint=rotated["endpoint"], user_key="local",
+ ) is None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn, endpoint=other["endpoint"], user_key="local",
+ ) is not None
def test_web_push_status_sync_disables_previous_endpoint_for_same_device(monkeypatch, tmp_path):
@@ -3468,9 +3523,13 @@ def test_web_push_status_sync_disables_client_known_previous_endpoint(monkeypatc
) is not None
-def test_web_push_status_sync_does_not_reenable_disabled_endpoint(monkeypatch, tmp_path):
[email protected]("provider_invalidated", [True, False])
+def test_web_push_status_sync_does_not_reenable_disabled_endpoint(
+ monkeypatch, tmp_path, provider_invalidated
+):
from storage import web_push_service
from storage.db import create_sqlite_engine
+ from storage.models import web_push_subscriptions
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
ensure_sqlite_state()
@@ -3491,6 +3550,12 @@ def test_web_push_status_sync_does_not_reenable_disabled_endpoint(monkeypatch, t
engine = create_sqlite_engine()
with engine.begin() as conn:
web_push_service.mark_send_failure(conn, endpoint=subscription["endpoint"], disable=True)
+ if not provider_invalidated:
+ conn.execute(
+ web_push_subscriptions.update()
+ .where(web_push_subscriptions.c.endpoint == subscription["endpoint"])
+ .values(provider_invalidated_at=None)
+ )
status = client.post(
"/api/web-push/status",
@@ -3505,6 +3570,7 @@ def test_web_push_status_sync_does_not_reenable_disabled_endpoint(monkeypatch, t
assert status.status_code == 200
assert status.get_json()["subscription_count"] == 0
assert status.get_json()["current_subscription_enabled"] is False
+ assert status.get_json()["current_subscription_repairable"] is provider_invalidated
with engine.connect() as conn:
assert web_push_service.get_enabled_by_endpoint(
conn,
@@ -3513,6 +3579,57 @@ def test_web_push_status_sync_does_not_reenable_disabled_endpoint(monkeypatch, t
) is None
+def test_web_push_background_rotation_preserves_logout_opt_out(monkeypatch, tmp_path):
+ from storage import web_push_service
+ from storage.db import create_sqlite_engine
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+
+ client = app.test_client()
+ headers = csrf_headers(client)
+ previous = {
+ "endpoint": "https://push.example.test/sub/previous",
+ "keys": {"p256dh": "previous-key", "auth": "previous-auth"},
+ }
+ current = {
+ "endpoint": "https://push.example.test/sub/current",
+ "keys": {"p256dh": "current-key", "auth": "current-auth"},
+ }
+ assert client.post(
+ "/api/web-push/subscriptions",
+ json={"subscription": previous, "device_id": "device-1"},
+ headers=headers,
+ ).status_code == 200
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ assert web_push_service.disable_subscription(
+ conn,
+ endpoint=previous["endpoint"],
+ user_key="local",
+ ) is True
+
+ rotated = client.post(
+ "/api/web-push/subscriptions",
+ json={
+ "subscription": current,
+ "previous_endpoints": [previous["endpoint"]],
+ "background_rotation": True,
+ },
+ headers=headers,
+ )
+
+ assert rotated.status_code == 200
+ assert rotated.get_json() == {
+ "accepted": False,
+ "ok": True,
+ "subscription": None,
+ }
+ with engine.connect() as conn:
+ assert web_push_service.count_enabled(conn, user_key="local") == 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
diff --git a/tests/test_web_push_provider_invalidation_migration.py b/tests/test_web_push_provider_invalidation_migration.py
new file mode 100644
index 000000000..739a0eda7
--- /dev/null
+++ b/tests/test_web_push_provider_invalidation_migration.py
@@ -0,0 +1,84 @@
+"""Existing disabled Web Push rows must not gain repair consent on upgrade."""
+
+import sqlite3
+
+import pytest
+from alembic import command
+
+from storage import migrations, web_push_service
+from storage.db import create_sqlite_engine
+
+
+pytestmark = pytest.mark.no_sqlite_template
+
+
+def test_upgrade_keeps_legacy_disabled_failure_opted_out(tmp_path):
+ path = tmp_path / "state.sqlite"
+ migrations.run_migrations(path, revision="20260907_0061")
+ with sqlite3.connect(path) as conn:
+ conn.executemany(
+ """
+ insert into web_push_subscriptions (
+ id, user_key, endpoint, p256dh, auth, enabled, last_failure_at,
+ failure_count, created_at, updated_at
+ ) values (?, 'remote:user-a', ?, 'key', 'auth', ?, ?, 1, 'old', 'old')
+ """,
+ [
+ (
+ "opted-out",
+ "https://push.example.test/sub/opted-out",
+ 0,
+ "2026-09-01T00:00:00Z",
+ ),
+ (
+ "still-enabled",
+ "https://push.example.test/sub/still-enabled",
+ 1,
+ "2026-09-01T00:00:00Z",
+ ),
+ ],
+ )
+
+ migrations.run_migrations(path)
+ engine = create_sqlite_engine(path)
+ with engine.begin() as conn:
+ disabled = web_push_service.get_by_endpoint(
+ conn,
+ endpoint="https://push.example.test/sub/opted-out",
+ user_key="remote:user-a",
+ )
+ assert disabled is not None
+ assert disabled["last_failure_at"] is not None
+ assert disabled["provider_invalidated_at"] is None
+ assert web_push_service.upsert_background_rotated_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload={
+ "endpoint": "https://push.example.test/sub/rotated",
+ "keys": {"p256dh": "key", "auth": "auth"},
+ },
+ previous_endpoints=[disabled["endpoint"]],
+ ) is None
+ enabled = web_push_service.get_by_endpoint(
+ conn,
+ endpoint="https://push.example.test/sub/still-enabled",
+ user_key="remote:user-a",
+ )
+ assert enabled is not None
+ assert enabled["enabled"] is True
+ web_push_service.mark_send_failure(conn, endpoint=enabled["endpoint"], disable=True)
+ with sqlite3.connect(path) as conn:
+ assert conn.execute("select version_num from alembic_version").fetchone() == (
+ "20260923_0062",
+ )
+
+ command.downgrade(migrations.alembic_config(path), "20260907_0061")
+ with sqlite3.connect(path) as conn:
+ assert conn.execute(
+ "select provider_invalidated_at from web_push_subscriptions where id = 'still-enabled'"
+ ).fetchone() == (None,)
+ migrations.run_migrations(path)
+ with sqlite3.connect(path) as conn:
+ assert conn.execute(
+ "select provider_invalidated_at from web_push_subscriptions where id = 'still-enabled'"
+ ).fetchone() == (None,)
diff --git a/tests/test_web_push_service.py b/tests/test_web_push_service.py
index 7f0902d86..f11c91eb1 100644
--- a/tests/test_web_push_service.py
+++ b/tests/test_web_push_service.py
@@ -53,6 +53,135 @@ def test_subscription_upsert_and_disable(tmp_path):
assert web_push_service.count_enabled(conn, user_key="local") == 0
+def test_explicit_disable_clears_delivery_failure_marker(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ row = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload(),
+ device_id="device-1",
+ )
+ web_push_service.mark_send_failure(conn, endpoint=row["endpoint"], disable=True)
+
+ assert web_push_service.disable_device_subscription(
+ conn,
+ user_key="remote:user-a",
+ device_id="device-1",
+ ) is True
+
+ disabled = web_push_service.get_by_endpoint(
+ conn,
+ endpoint=row["endpoint"],
+ user_key="remote:user-a",
+ )
+ assert disabled is not None
+ assert disabled["enabled"] is False
+ assert disabled["last_failure_at"] is None
+ assert disabled["provider_invalidated_at"] is None
+
+
+def test_late_provider_failure_does_not_undo_logout_opt_out(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ row = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload(),
+ device_id="device-1",
+ )
+ assert web_push_service.disable_device_subscription(
+ conn,
+ user_key="remote:user-a",
+ device_id="device-1",
+ )
+ web_push_service.mark_send_failure(conn, endpoint=row["endpoint"], disable=True)
+ disabled = web_push_service.get_by_endpoint(
+ conn,
+ endpoint=row["endpoint"],
+ user_key="remote:user-a",
+ )
+ assert disabled is not None
+ assert disabled["enabled"] is False
+ assert disabled["provider_invalidated_at"] is None
+
+
+def test_late_send_success_preserves_provider_invalidation(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ row = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload(),
+ )
+ web_push_service.mark_send_failure(conn, endpoint=row["endpoint"], disable=True)
+ invalidated = web_push_service.get_by_endpoint(
+ conn, endpoint=row["endpoint"], user_key="remote:user-a"
+ )
+ assert invalidated is not None
+ assert invalidated["provider_invalidated_at"] is not None
+ web_push_service.mark_send_success(conn, endpoint=row["endpoint"])
+ after_success = web_push_service.get_by_endpoint(
+ conn, endpoint=row["endpoint"], user_key="remote:user-a"
+ )
+ assert after_success is not None
+ assert after_success["enabled"] is False
+ assert after_success["provider_invalidated_at"] == invalidated["provider_invalidated_at"]
+ assert after_success["last_failure_at"] == invalidated["last_failure_at"]
+
+
[email protected]("submitted_device_id", ["device-1", "stale-device"])
+def test_logout_disables_rotated_endpoint_when_old_endpoint_was_submitted(
+ tmp_path, submitted_device_id
+):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ previous = web_push_service.upsert_subscription(
+ conn, user_key="remote:user-a", payload=_payload("https://push.example.test/sub/old"),
+ device_id="device-1",
+ )
+ rotated = web_push_service.upsert_background_rotated_subscription(
+ conn, user_key="remote:user-a", payload=_payload("https://push.example.test/sub/new"),
+ previous_endpoints=[previous["endpoint"]],
+ )
+ assert rotated is not None
+ assert rotated["device_id"] == "device-1"
+ other_device = web_push_service.upsert_subscription(
+ conn, user_key="remote:user-a", payload=_payload("https://push.example.test/sub/other"),
+ device_id="device-2",
+ )
+ other_user = web_push_service.upsert_subscription(
+ conn, user_key="remote:user-b", payload=_payload("https://push.example.test/sub/user-b"),
+ device_id="device-1",
+ )
+
+ assert web_push_service.disable_device_subscription(
+ conn, user_key="remote:user-a", endpoint=previous["endpoint"],
+ device_id=submitted_device_id,
+ )
+ assert web_push_service.get_enabled_by_endpoint(
+ conn, endpoint=rotated["endpoint"], user_key="remote:user-a",
+ ) is None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn, endpoint=other_device["endpoint"], user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn, endpoint=other_user["endpoint"], user_key="remote:user-b",
+ ) is not None
+
+
def test_subscription_upsert_disables_previous_endpoint_for_same_device(tmp_path):
db = tmp_path / "vibe.sqlite"
run_migrations(db)
@@ -122,6 +251,79 @@ def test_attach_device_to_enabled_subscription_does_not_reenable_disabled_endpoi
assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 0
+def test_background_rotation_requires_active_or_provider_failed_previous(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ previous = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/previous"),
+ device_id="device-1",
+ )
+ current = _payload("https://push.example.test/sub/current")
+
+ accepted = web_push_service.upsert_background_rotated_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=current,
+ previous_endpoints=[previous["endpoint"]],
+ )
+ assert accepted is not None
+ assert accepted["endpoint"] == current["endpoint"]
+ assert accepted["device_id"] == "device-1"
+
+ web_push_service.disable_subscription(
+ conn,
+ endpoint=accepted["endpoint"],
+ user_key="remote:user-a",
+ )
+ rejected = web_push_service.upsert_background_rotated_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/next"),
+ previous_endpoints=[accepted["endpoint"]],
+ )
+ assert rejected is None
+
+
+def test_background_rotation_accepts_provider_failed_previous(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ previous = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/previous"),
+ device_id="device-1",
+ )
+ web_push_service.mark_send_failure(
+ conn,
+ endpoint=previous["endpoint"],
+ disable=True,
+ )
+
+ accepted = web_push_service.upsert_background_rotated_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ previous_endpoints=[previous["endpoint"]],
+ )
+
+ assert accepted is not None
+ assert accepted["endpoint"] == "https://push.example.test/sub/current"
+ assert accepted["device_id"] == "device-1"
+ consumed = web_push_service.get_by_endpoint(
+ conn, endpoint=previous["endpoint"], user_key="remote:user-a",
+ )
+ assert consumed is not None
+ assert consumed["provider_invalidated_at"] is None
+
+
def test_attach_device_to_enabled_subscription_preserves_same_origin_legacy_rows(tmp_path):
db = tmp_path / "vibe.sqlite"
run_migrations(db)
@@ -222,7 +424,7 @@ def test_attach_device_to_enabled_subscription_disables_client_known_previous_en
assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 2
-def test_attach_device_to_enabled_subscription_cleans_previous_endpoint_when_current_unknown(tmp_path):
+def test_attach_device_to_enabled_subscription_recovers_unknown_rotated_endpoint(tmp_path):
db = tmp_path / "vibe.sqlite"
run_migrations(db)
engine = create_sqlite_engine(db)
@@ -232,6 +434,51 @@ def test_attach_device_to_enabled_subscription_cleans_previous_endpoint_when_cur
conn,
user_key="remote:user-a",
payload=_payload("https://push.example.test/sub/previous"),
+ device_id="device-1",
+ )
+
+ synced = web_push_service.attach_device_to_enabled_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ device_id="device-1",
+ previous_endpoints=[previous["endpoint"]],
+ )
+
+ assert synced is not None
+ assert synced["endpoint"] == "https://push.example.test/sub/current"
+ assert synced["device_id"] == "device-1"
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=previous["endpoint"],
+ user_key="remote:user-a",
+ ) is None
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=synced["endpoint"],
+ user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 1
+
+
+def test_attach_device_to_enabled_subscription_recovers_after_provider_disabled_previous(
+ tmp_path,
+):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ previous = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/previous"),
+ device_id="device-1",
+ )
+ web_push_service.mark_send_failure(
+ conn,
+ endpoint=previous["endpoint"],
+ disable=True,
)
synced = web_push_service.attach_device_to_enabled_subscription(
@@ -242,13 +489,109 @@ def test_attach_device_to_enabled_subscription_cleans_previous_endpoint_when_cur
previous_endpoints=[previous["endpoint"]],
)
+ assert synced is not None
+ assert synced["endpoint"] == "https://push.example.test/sub/current"
+ assert web_push_service.get_enabled_by_endpoint(
+ conn,
+ endpoint=synced["endpoint"],
+ user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 1
+
+
[email protected]("repair_mode", ["foreground", "background"])
+def test_repair_consumes_previous_invalidation_before_later_logout(tmp_path, repair_mode):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ previous = web_push_service.upsert_subscription(
+ conn, user_key="remote:user-a", payload=_payload("https://push.example.test/sub/a"),
+ device_id="device-1",
+ )
+ web_push_service.mark_send_failure(conn, endpoint=previous["endpoint"], disable=True)
+ replacement = _payload("https://push.example.test/sub/b")
+ if repair_mode == "foreground":
+ repaired = web_push_service.attach_device_to_enabled_subscription(
+ conn, user_key="remote:user-a", payload=replacement, device_id="device-1",
+ previous_endpoints=[previous["endpoint"]],
+ )
+ else:
+ repaired = web_push_service.upsert_background_rotated_subscription(
+ conn, user_key="remote:user-a", payload=replacement,
+ previous_endpoints=[previous["endpoint"]],
+ )
+ assert repaired is not None
+ consumed = web_push_service.get_by_endpoint(
+ conn, endpoint=previous["endpoint"], user_key="remote:user-a",
+ )
+ assert consumed is not None
+ assert consumed["provider_invalidated_at"] is None
+ assert web_push_service.disable_device_subscription(
+ conn, user_key="remote:user-a", device_id="device-1",
+ )
+ assert web_push_service.attach_device_to_enabled_subscription(
+ conn, user_key="remote:user-a", payload=_payload("https://push.example.test/sub/c"),
+ device_id="device-1", previous_endpoints=[repaired["endpoint"], previous["endpoint"]],
+ ) is None
+ assert web_push_service.upsert_background_rotated_subscription(
+ conn, user_key="remote:user-a", payload=_payload("https://push.example.test/sub/c"),
+ previous_endpoints=[repaired["endpoint"], previous["endpoint"]],
+ ) is None
+
+
+def test_attach_device_to_enabled_subscription_does_not_cross_devices(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ previous = web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/previous"),
+ device_id="device-1",
+ )
+
+ synced = web_push_service.attach_device_to_enabled_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload=_payload("https://push.example.test/sub/current"),
+ device_id="device-2",
+ previous_endpoints=[previous["endpoint"]],
+ )
+
assert synced is None
assert web_push_service.get_enabled_by_endpoint(
conn,
endpoint=previous["endpoint"],
user_key="remote:user-a",
+ ) is not None
+ assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 1
+
+
+def test_failed_foreground_reconciliation_preserves_invalidation(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ with engine.begin() as conn:
+ previous = web_push_service.upsert_subscription(
+ conn, user_key="remote:user-a", payload=_payload("https://push.example.test/sub/previous"),
+ device_id="device-1",
+ )
+ web_push_service.mark_send_failure(conn, endpoint=previous["endpoint"], disable=True)
+
+ assert web_push_service.attach_device_to_enabled_subscription(
+ conn, user_key="remote:user-a", payload=_payload("https://push.example.test/sub/current"),
+ device_id="device-2", previous_endpoints=[previous["endpoint"]],
) is None
- assert web_push_service.count_enabled(conn, user_key="remote:user-a") == 0
+ remaining = web_push_service.get_by_endpoint(
+ conn, endpoint=previous["endpoint"], user_key="remote:user-a",
+ )
+ assert remaining is not None
+ assert remaining["provider_invalidated_at"] is not None
def test_attach_device_to_enabled_subscription_preserves_existing_label_when_missing(tmp_path):
diff --git a/ui/public/push-sw.js b/ui/public/push-sw.js
index 05c50eb20..fe8582a83 100644
--- a/ui/public/push-sw.js
+++ b/ui/public/push-sw.js
@@ -17,6 +17,150 @@ function syncAppBadge(count) {
const WEB_PUSH_LAUNCH_CACHE = 'avibe.web-push-launch.v1';
const WEB_PUSH_LAUNCH_ENTRY_PATH = '/__avibe/web-push-launch';
+const WEB_PUSH_ENDPOINT_CACHE = 'avibe.web-push-endpoint.v1';
+const WEB_PUSH_ENDPOINT_ENTRY_PATH = '/__avibe/web-push-endpoint';
+
+function endpointCacheUrl() {
+ return new URL(WEB_PUSH_ENDPOINT_ENTRY_PATH, self.location.origin).href;
+}
+
+async function rememberedPushEndpoint() {
+ if (!self.caches) return null;
+ try {
+ const cache = await self.caches.open(WEB_PUSH_ENDPOINT_CACHE);
+ const response = await cache.match(endpointCacheUrl());
+ const payload = response ? await response.json() : null;
+ return typeof payload?.endpoint === 'string' && payload.endpoint ? payload.endpoint : null;
+ } catch {
+ return null;
+ }
+}
+
+async function rememberPushEndpoint(endpoint) {
+ if (!self.caches || !endpoint) return;
+ try {
+ const cache = await self.caches.open(WEB_PUSH_ENDPOINT_CACHE);
+ await cache.put(endpointCacheUrl(), new Response(JSON.stringify({ endpoint }), {
+ headers: { 'content-type': 'application/json' },
+ }));
+ } catch {
+ // Foreground reconciliation remains available if Cache Storage fails.
+ }
+}
+
+function urlBase64ToUint8Array(value) {
+ const padding = '='.repeat((4 - (value.length % 4)) % 4);
+ const base64 = (value + padding).replace(/-/g, '+').replace(/_/g, '/');
+ const raw = self.atob(base64);
+ const output = new Uint8Array(raw.length);
+ for (let i = 0; i < raw.length; i += 1) output[i] = raw.charCodeAt(i);
+ return output;
+}
+
+function arrayBuffersEqual(left, right) {
+ 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;
+}
+
+async function fetchCsrfToken() {
+ const response = await fetch('/api/csrf-token', {
+ credentials: 'same-origin',
+ });
+ if (!response.ok) throw new Error(`CSRF token request failed (${response.status})`);
+ const payload = await response.json();
+ if (typeof payload?.csrf_token !== 'string' || !payload.csrf_token) {
+ throw new Error('CSRF token missing from response');
+ }
+ return payload.csrf_token;
+}
+
+async function isInvalidCsrfResponse(response) {
+ if (response.status !== 403 || typeof response.json !== 'function') return false;
+ try {
+ const payload = await response.json();
+ return payload?.message === 'Forbidden: invalid csrf token';
+ } catch {
+ return false;
+ }
+}
+
+async function postPushSubscription(subscription, previousEndpoints, csrfToken) {
+ return fetch('/api/web-push/subscriptions', {
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: {
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ 'X-Vibe-CSRF-Token': csrfToken,
+ },
+ body: JSON.stringify({
+ subscription: subscription.toJSON(),
+ previous_endpoints: previousEndpoints,
+ background_rotation: true,
+ }),
+ });
+}
+
+async function syncPushSubscription(subscription, previousEndpoints) {
+ let csrfToken = await fetchCsrfToken();
+ let response = await postPushSubscription(subscription, previousEndpoints, csrfToken);
+ if (
+ !response.ok
+ && await isInvalidCsrfResponse(response)
+ ) {
+ csrfToken = await fetchCsrfToken();
+ response = await postPushSubscription(subscription, previousEndpoints, csrfToken);
+ }
+ if (!response.ok) throw new Error(`Push subscription sync failed (${response.status})`);
+ const payload = await response.json();
+ return payload?.accepted !== false;
+}
+
+async function fetchVapidPublicKey() {
+ const response = await fetch('/api/web-push/vapid-public-key', {
+ credentials: 'same-origin',
+ });
+ if (!response.ok) throw new Error(`VAPID key request failed (${response.status})`);
+ const payload = await response.json();
+ if (typeof payload?.public_key !== 'string' || !payload.public_key) {
+ throw new Error('VAPID public key missing from response');
+ }
+ return urlBase64ToUint8Array(payload.public_key);
+}
+
+async function replacementSubscription(event) {
+ const applicationServerKey = await fetchVapidPublicKey();
+ const replacement = event.newSubscription;
+ if (
+ replacement
+ && arrayBuffersEqual(replacement.options?.applicationServerKey, applicationServerKey)
+ ) {
+ return replacement;
+ }
+ if (replacement) {
+ await replacement.unsubscribe();
+ const remaining = await self.registration.pushManager.getSubscription();
+ if (remaining?.endpoint === replacement.endpoint) {
+ throw new Error('Stale push subscription was not removed');
+ }
+ }
+ const current = await self.registration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey,
+ });
+ if (
+ !arrayBuffersEqual(current.options?.applicationServerKey, applicationServerKey)
+ || (replacement && current.endpoint === replacement.endpoint)
+ ) {
+ throw new Error('Push subscription replacement is still stale');
+ }
+ return current;
+}
// iOS may honor an installed PWA's manifest start URL instead of the path passed
// to openWindow(). Leave a short-lived launch handoff in Cache Storage so the
@@ -33,6 +177,20 @@ function rememberPendingNotificationLaunch(url) {
.catch(() => {});
}
+self.addEventListener('pushsubscriptionchange', (event) => {
+ event.waitUntil(
+ (async () => {
+ const previousEndpoint = event.oldSubscription?.endpoint ?? await rememberedPushEndpoint();
+ const subscription = await replacementSubscription(event);
+ const accepted = await syncPushSubscription(
+ subscription,
+ previousEndpoint ? [previousEndpoint] : [],
+ );
+ if (accepted) await rememberPushEndpoint(subscription.endpoint);
+ })().catch(() => undefined),
+ );
+});
+
self.addEventListener('push', (event) => {
let payload = {};
try {
diff --git a/ui/src/components/workbench/WebPushControl.test.tsx b/ui/src/components/workbench/WebPushControl.test.tsx
new file mode 100644
index 000000000..be4e421a0
--- /dev/null
+++ b/ui/src/components/workbench/WebPushControl.test.tsx
@@ -0,0 +1,159 @@
+/** @vitest-environment jsdom */
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { WebPushControl } from './WebPushControl';
+
+const { api, push } = vi.hoisted(() => ({
+ api: { getWebPushStatus: vi.fn() },
+ push: {
+ disableWebPush: vi.fn(),
+ enableWebPush: vi.fn(),
+ getWebPushDeviceId: vi.fn(),
+ getRememberedWebPushEndpoints: vi.fn(),
+ getExistingWebPushSubscription: vi.fn(),
+ getWebPushSupportState: vi.fn(),
+ rememberWebPushEndpoint: vi.fn(),
+ webPushSubscriptionUsesVapidKey: vi.fn(),
+ },
+}));
+
+vi.mock('@/context/ApiContext', () => ({ useApi: () => api }));
+vi.mock('@/context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => ({ capabilities: { can_read_instance: true } }),
+}));
+vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/lib/webPush', () => push);
+
+const oldEndpoint = 'https://push.example.test/sub/old';
+const newEndpoint = 'https://push.example.test/sub/new';
+const oldSubscription = {
+ endpoint: oldEndpoint,
+ toJSON: () => ({ endpoint: oldEndpoint }),
+};
+const newSubscription = {
+ endpoint: newEndpoint,
+ toJSON: () => ({ endpoint: newEndpoint }),
+};
+
+const status = (enabled: boolean, repairable = false) => ({
+ ok: true,
+ configured: true,
+ public_key: 'new-key',
+ subscription_count: enabled ? 1 : 0,
+ current_subscription_enabled: enabled,
+ current_subscription_repairable: repairable,
+});
+
+beforeEach(() => {
+ vi.stubGlobal('Notification', { permission: 'granted' });
+ push.getWebPushSupportState.mockReturnValue({
+ supported: true,
+ standalone: false,
+ requiresStandalone: false,
+ });
+ push.getWebPushDeviceId.mockResolvedValue('device-1');
+ push.getRememberedWebPushEndpoints.mockResolvedValue([oldEndpoint]);
+ push.getExistingWebPushSubscription.mockResolvedValue(null);
+ push.enableWebPush.mockResolvedValue(undefined);
+ push.rememberWebPushEndpoint.mockResolvedValue(undefined);
+ push.webPushSubscriptionUsesVapidKey.mockReturnValue(true);
+ api.getWebPushStatus.mockResolvedValue(status(false));
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('WebPushControl recovery', () => {
+ it('recreates a missing subscription only when its remembered endpoint is still enabled', async () => {
+ push.getExistingWebPushSubscription
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(newSubscription);
+ api.getWebPushStatus
+ .mockResolvedValueOnce(status(true))
+ .mockResolvedValueOnce(status(true));
+
+ render(<WebPushControl />);
+
+ await screen.findByText('workbench.inbox.notifications.enabled');
+ expect(api.getWebPushStatus).toHaveBeenNthCalledWith(1, { endpoint: oldEndpoint });
+ expect(push.enableWebPush).toHaveBeenCalledWith(api, {
+ forceResubscribe: false,
+ recoverOnly: true,
+ });
+ expect(api.getWebPushStatus).toHaveBeenNthCalledWith(2, {
+ endpoint: newEndpoint,
+ subscription: newSubscription.toJSON(),
+ device_id: 'device-1',
+ previous_endpoints: [oldEndpoint],
+ });
+ });
+
+ it('keeps a missing subscription disabled after opt-out', async () => {
+ render(<WebPushControl />);
+
+ await screen.findByText('workbench.inbox.notifications.enable');
+ expect(api.getWebPushStatus).toHaveBeenCalledWith({ endpoint: oldEndpoint });
+ expect(push.enableWebPush).not.toHaveBeenCalled();
+ });
+
+ it('replaces an enabled subscription bound to an obsolete VAPID key', async () => {
+ push.getExistingWebPushSubscription
+ .mockResolvedValueOnce(oldSubscription)
+ .mockResolvedValueOnce(newSubscription);
+ push.webPushSubscriptionUsesVapidKey.mockReturnValue(false);
+ api.getWebPushStatus
+ .mockResolvedValueOnce(status(true))
+ .mockResolvedValueOnce(status(true));
+
+ render(<WebPushControl />);
+
+ await screen.findByText('workbench.inbox.notifications.enabled');
+ expect(push.webPushSubscriptionUsesVapidKey).toHaveBeenCalledWith(oldSubscription, 'new-key');
+ expect(push.enableWebPush).toHaveBeenCalledWith(api, {
+ forceResubscribe: true,
+ recoverOnly: true,
+ });
+ });
+
+ it('does not revive an opted-out subscription with an obsolete key', async () => {
+ push.getExistingWebPushSubscription.mockResolvedValue(oldSubscription);
+ push.webPushSubscriptionUsesVapidKey.mockReturnValue(false);
+
+ render(<WebPushControl />);
+
+ await screen.findByText('workbench.inbox.notifications.enable');
+ expect(push.enableWebPush).not.toHaveBeenCalled();
+ });
+
+ it('shows disabled when a conditional repair fails after the initial status check', async () => {
+ push.getExistingWebPushSubscription.mockResolvedValue(oldSubscription);
+ push.webPushSubscriptionUsesVapidKey.mockReturnValue(false);
+ push.enableWebPush.mockRejectedValue(new Error('recovery_not_authorized'));
+ api.getWebPushStatus.mockResolvedValue(status(true));
+
+ render(<WebPushControl />);
+
+ await screen.findByText('workbench.inbox.notifications.enable');
+ await waitFor(() => expect(push.enableWebPush).toHaveBeenCalledOnce());
+ });
+
+ it('does not report an initial enabled row after the replacement loses authorization', async () => {
+ push.getExistingWebPushSubscription
+ .mockResolvedValueOnce(oldSubscription)
+ .mockResolvedValueOnce(newSubscription);
+ push.webPushSubscriptionUsesVapidKey.mockReturnValue(false);
+ api.getWebPushStatus
+ .mockResolvedValueOnce(status(true))
+ .mockResolvedValueOnce(status(false));
+
+ render(<WebPushControl />);
+
+ await screen.findByText('workbench.inbox.notifications.enable');
+ expect(push.rememberWebPushEndpoint).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/workbench/WebPushControl.tsx b/ui/src/components/workbench/WebPushControl.tsx
index 652191f62..dea04c416 100644
--- a/ui/src/components/workbench/WebPushControl.tsx
+++ b/ui/src/components/workbench/WebPushControl.tsx
@@ -15,6 +15,7 @@ import {
getExistingWebPushSubscription,
getWebPushSupportState,
rememberWebPushEndpoint,
+ webPushSubscriptionUsesVapidKey,
type WebPushSupportState,
} from '@/lib/webPush';
@@ -39,20 +40,55 @@ export const WebPushControl: React.FC = () => {
return;
}
const existing = await getExistingWebPushSubscription();
+ const previousEndpoints = await getRememberedWebPushEndpoints();
+ const rememberedEndpoint = previousEndpoints[0];
const serverStatus = await api
.getWebPushStatus(
existing
? {
endpoint: existing.endpoint,
subscription: existing.toJSON(),
- device_id: getWebPushDeviceId(),
- previous_endpoints: getRememberedWebPushEndpoints(),
+ device_id: await getWebPushDeviceId(),
+ previous_endpoints: previousEndpoints,
}
- : undefined,
+ : rememberedEndpoint ? { endpoint: rememberedEndpoint } : undefined,
)
.catch(() => null);
+ const repairable = Boolean(serverStatus && (
+ serverStatus.current_subscription_repairable
+ || (!existing && Boolean(rememberedEndpoint) && serverStatus.current_subscription_enabled)
+ || (existing && serverStatus.current_subscription_enabled
+ && !webPushSubscriptionUsesVapidKey(existing, serverStatus.public_key))
+ ));
+ if (
+ repairable
+ && typeof Notification !== 'undefined'
+ && Notification.permission === 'granted'
+ ) {
+ try {
+ await enableWebPush(api, { forceResubscribe: Boolean(existing), recoverOnly: true });
+ const repaired = await getExistingWebPushSubscription();
+ if (repaired) {
+ const repairedStatus = await api.getWebPushStatus({
+ endpoint: repaired.endpoint,
+ subscription: repaired.toJSON(),
+ device_id: await getWebPushDeviceId(),
+ previous_endpoints: await getRememberedWebPushEndpoints(),
+ });
+ if (repairedStatus.current_subscription_enabled) {
+ await rememberWebPushEndpoint(repaired.endpoint);
+ setStatus('enabled');
+ return;
+ }
+ }
+ } catch {
+ // Keep the control recoverable; the user can still retry manually.
+ }
+ setStatus('disabled');
+ return;
+ }
if (existing && serverStatus?.current_subscription_enabled) {
- rememberWebPushEndpoint(existing.endpoint);
+ await rememberWebPushEndpoint(existing.endpoint);
}
setStatus(existing && serverStatus?.current_subscription_enabled ? 'enabled' : 'disabled');
};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 3d4770ba7..c00f0f379 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -536,8 +536,9 @@ export type ApiContextType = {
deviceLabel?: string,
deviceId?: string,
previousEndpoints?: string[],
+ backgroundRotation?: boolean,
) => Promise<WebPushSubscriptionResult>;
- unsubscribeWebPush: (endpoint: string) => Promise<{ ok: boolean; disabled: boolean }>;
+ unsubscribeWebPush: (endpoint: string, deviceId?: string) => Promise<{ ok: boolean; disabled: boolean }>;
sendWebPushTest: (payload?: { title?: string; body?: string; url?: string; endpoint?: string }) => Promise<WebPushTestResult>;
setShowPageAvailability: (sessionId: string, offline: boolean) => Promise<any>;
/** Read the session's Show Page without creating it; rejects with
@@ -2607,6 +2608,7 @@ export type WebPushStatus = {
public_key: string;
subscription_count: number;
current_subscription_enabled?: boolean;
+ current_subscription_repairable?: boolean;
normal_delivery?: WebPushNormalDelivery;
};
@@ -2620,6 +2622,7 @@ export type WebPushStatusPayload = {
export type WebPushSubscriptionResult = {
ok: boolean;
+ accepted: boolean;
subscription: {
id: string;
user_key: string;
@@ -2628,7 +2631,7 @@ export type WebPushSubscriptionResult = {
device_id?: string | null;
user_agent?: string | null;
device_label?: string | null;
- };
+ } | null;
};
export type WebPushTestResult = {
@@ -3754,14 +3757,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getWebPushStatus: (payload) =>
payload ? postJson('/api/web-push/status', payload) : getJson('/api/web-push/status'),
getWebPushVapidPublicKey: () => getJson('/api/web-push/vapid-public-key'),
- subscribeWebPush: (subscription, deviceLabel, deviceId, previousEndpoints) =>
+ subscribeWebPush: (subscription, deviceLabel, deviceId, previousEndpoints, backgroundRotation) =>
postJson('/api/web-push/subscriptions', {
subscription,
device_label: deviceLabel,
device_id: deviceId,
previous_endpoints: previousEndpoints,
+ background_rotation: backgroundRotation,
}),
- unsubscribeWebPush: (endpoint) => deleteJson('/api/web-push/subscriptions', { endpoint }),
+ unsubscribeWebPush: (endpoint, deviceId) =>
+ deleteJson('/api/web-push/subscriptions', { endpoint, device_id: deviceId }),
sendWebPushTest: (payload) => postJson('/api/web-push/test', payload ?? {}),
setShowPageAvailability: (sessionId, offline) => postJson(
`/api/show-pages/${encodeURIComponent(sessionId)}/availability`,
@@ -4532,7 +4537,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
// Logout remains authoritative when Push APIs are unavailable.
}
return postJson('/auth/logout', {
- device_id: getWebPushDeviceId(),
+ device_id: await getWebPushDeviceId(),
...(endpoint ? { endpoint } : {}),
});
},
diff --git a/ui/src/lib/pushServiceWorker.test.ts b/ui/src/lib/pushServiceWorker.test.ts
index cf2063f01..3f0ad7b8d 100644
--- a/ui/src/lib/pushServiceWorker.test.ts
+++ b/ui/src/lib/pushServiceWorker.test.ts
@@ -50,4 +50,352 @@ describe('push service worker notification launches', () => {
url: '/chat/session-3',
});
});
+
+ it('syncs a replacement subscription and retires the old endpoint', async () => {
+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');
+ const handlers = new Map<string, (event: unknown) => void>();
+ const requests: Array<{ input: string; init?: RequestInit }> = [];
+ const newSubscription = {
+ endpoint: 'https://push.example.test/sub/new',
+ options: { applicationServerKey: new Uint8Array([1, 2, 3, 4]).buffer },
+ toJSON: () => ({
+ endpoint: 'https://push.example.test/sub/new',
+ keys: { p256dh: 'new-key', auth: 'new-auth' },
+ }),
+ };
+ const worker = {
+ location: { origin: 'https://avibe.local' },
+ caches: { open: vi.fn() },
+ clients: { matchAll: vi.fn(), openWindow: vi.fn() },
+ registration: { showNotification: vi.fn(), pushManager: { subscribe: vi.fn() } },
+ atob,
+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),
+ };
+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {
+ requests.push({ input, init });
+ if (input === '/api/csrf-token') {
+ return { ok: true, json: async () => ({ csrf_token: 'csrf-token' }) };
+ }
+ if (input === '/api/web-push/vapid-public-key') {
+ return { ok: true, json: async () => ({ public_key: 'AQIDBA' }) };
+ }
+ return { ok: true, json: async () => ({}) };
+ });
+
+ runInNewContext(source, {
+ self: worker,
+ fetch: fetchMock,
+ navigator: {},
+ URL,
+ Response,
+ Date,
+ Number,
+ JSON,
+ Promise,
+ Uint8Array,
+ });
+
+ let completion: Promise<unknown> | undefined;
+ handlers.get('pushsubscriptionchange')?.({
+ newSubscription,
+ oldSubscription: { endpoint: 'https://push.example.test/sub/old' },
+ waitUntil: (promise: Promise<unknown>) => {
+ completion = promise;
+ },
+ });
+ await completion;
+
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(requests[0].input).toBe('/api/web-push/vapid-public-key');
+ expect(requests[1].input).toBe('/api/csrf-token');
+ expect(requests[2]).toMatchObject({
+ input: '/api/web-push/subscriptions',
+ init: {
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: {
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ 'X-Vibe-CSRF-Token': 'csrf-token',
+ },
+ },
+ });
+ expect(JSON.parse(String(requests[2].init?.body))).toEqual({
+ subscription: {
+ endpoint: 'https://push.example.test/sub/new',
+ keys: { p256dh: 'new-key', auth: 'new-auth' },
+ },
+ previous_endpoints: ['https://push.example.test/sub/old'],
+ background_rotation: true,
+ });
+ });
+
+ it('uses the last confirmed endpoint when the rotation event has no old subscription', async () => {
+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');
+ const handlers = new Map<string, (event: unknown) => void>();
+ const oldEndpoint = 'https://push.example.test/sub/old';
+ const newEndpoint = 'https://push.example.test/sub/new';
+ const cache = {
+ match: vi.fn(async () => Response.json({ endpoint: oldEndpoint })),
+ put: vi.fn(async () => undefined),
+ };
+ const subscription = {
+ endpoint: newEndpoint,
+ options: { applicationServerKey: new Uint8Array([1, 2, 3, 4]).buffer },
+ toJSON: () => ({
+ endpoint: newEndpoint,
+ keys: { p256dh: 'new-key', auth: 'new-auth' },
+ }),
+ };
+ const worker = {
+ location: { origin: 'https://avibe.local' },
+ caches: { open: vi.fn(async () => cache) },
+ registration: { pushManager: { subscribe: vi.fn() } },
+ atob,
+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),
+ };
+ const fetchMock = vi.fn(async (input: string, _init?: RequestInit) => {
+ if (input === '/api/web-push/vapid-public-key') {
+ return Response.json({ public_key: 'AQIDBA' });
+ }
+ if (input === '/api/csrf-token') {
+ return Response.json({ csrf_token: 'csrf-token' });
+ }
+ return Response.json({ accepted: true });
+ });
+ runInNewContext(source, {
+ self: worker,
+ fetch: fetchMock,
+ navigator: {},
+ URL,
+ Response,
+ Date,
+ Number,
+ JSON,
+ Promise,
+ Uint8Array,
+ });
+
+ let completion: Promise<unknown> | undefined;
+ handlers.get('pushsubscriptionchange')?.({
+ newSubscription: subscription,
+ oldSubscription: null,
+ waitUntil: (promise: Promise<unknown>) => {
+ completion = promise;
+ },
+ });
+ await completion;
+
+ expect(cache.match).toHaveBeenCalledWith('https://avibe.local/__avibe/web-push-endpoint');
+ expect(JSON.parse(String(fetchMock.mock.calls[2][1]?.body))).toMatchObject({
+ previous_endpoints: [oldEndpoint],
+ background_rotation: true,
+ });
+ expect(cache.put).toHaveBeenCalledWith(
+ 'https://avibe.local/__avibe/web-push-endpoint',
+ expect.any(Response),
+ );
+ expect(await cache.put.mock.calls[0][1].json()).toEqual({ endpoint: newEndpoint });
+ });
+
+ it('replaces a browser-provided subscription when its VAPID key is stale', async () => {
+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');
+ const handlers = new Map<string, (event: unknown) => void>();
+ const requests: Array<{ input: string; init?: RequestInit }> = [];
+ const staleSubscription = {
+ endpoint: 'https://push.example.test/sub/stale',
+ options: { applicationServerKey: new Uint8Array([9, 9, 9, 9]).buffer },
+ unsubscribe: vi.fn(async () => true),
+ toJSON: () => ({
+ endpoint: 'https://push.example.test/sub/stale',
+ keys: { p256dh: 'stale-key', auth: 'stale-auth' },
+ }),
+ };
+ const currentSubscription = {
+ endpoint: 'https://push.example.test/sub/current',
+ options: { applicationServerKey: new Uint8Array([1, 2, 3, 4]).buffer },
+ toJSON: () => ({
+ endpoint: 'https://push.example.test/sub/current',
+ keys: { p256dh: 'current-key', auth: 'current-auth' },
+ }),
+ };
+ const worker = {
+ location: { origin: 'https://avibe.local' },
+ caches: { open: vi.fn() },
+ clients: { matchAll: vi.fn(), openWindow: vi.fn() },
+ registration: {
+ showNotification: vi.fn(),
+ pushManager: {
+ getSubscription: vi.fn(async () => null),
+ subscribe: vi.fn(async () => currentSubscription),
+ },
+ },
+ atob,
+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),
+ };
+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {
+ requests.push({ input, init });
+ if (input === '/api/web-push/vapid-public-key') {
+ return { ok: true, json: async () => ({ public_key: 'AQIDBA' }) };
+ }
+ if (input === '/api/csrf-token') {
+ return { ok: true, json: async () => ({ csrf_token: 'csrf-token' }) };
+ }
+ return { ok: true, json: async () => ({}) };
+ });
+
+ runInNewContext(source, {
+ self: worker,
+ fetch: fetchMock,
+ navigator: {},
+ URL,
+ Response,
+ Date,
+ Number,
+ JSON,
+ Promise,
+ Uint8Array,
+ });
+
+ let completion: Promise<unknown> | undefined;
+ handlers.get('pushsubscriptionchange')?.({
+ newSubscription: staleSubscription,
+ oldSubscription: { endpoint: 'https://push.example.test/sub/old' },
+ waitUntil: (promise: Promise<unknown>) => {
+ completion = promise;
+ },
+ });
+ await completion;
+
+ expect(staleSubscription.unsubscribe).toHaveBeenCalledOnce();
+ expect(worker.registration.pushManager.subscribe).toHaveBeenCalledWith({
+ userVisibleOnly: true,
+ applicationServerKey: new Uint8Array([1, 2, 3, 4]),
+ });
+ expect(JSON.parse(String(requests[2].init?.body))).toEqual({
+ subscription: currentSubscription.toJSON(),
+ previous_endpoints: ['https://push.example.test/sub/old'],
+ background_rotation: true,
+ });
+ });
+
+ it('does not sync a stale subscription the browser refused to remove', async () => {
+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');
+ const handlers = new Map<string, (event: unknown) => void>();
+ const staleSubscription = {
+ endpoint: 'https://push.example.test/sub/stale',
+ options: { applicationServerKey: new Uint8Array([9, 9, 9, 9]).buffer },
+ unsubscribe: vi.fn(async () => false),
+ };
+ const pushManager = {
+ getSubscription: vi.fn(async () => staleSubscription),
+ subscribe: vi.fn(),
+ };
+ const worker = {
+ location: { origin: 'https://avibe.local' },
+ registration: { pushManager },
+ atob,
+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),
+ };
+ const fetchMock = vi.fn(async () => Response.json({ public_key: 'AQIDBA' }));
+ runInNewContext(source, {
+ self: worker,
+ fetch: fetchMock,
+ navigator: {},
+ URL,
+ Response,
+ Date,
+ Number,
+ JSON,
+ Promise,
+ Uint8Array,
+ });
+
+ let completion: Promise<unknown> | undefined;
+ handlers.get('pushsubscriptionchange')?.({
+ newSubscription: staleSubscription,
+ oldSubscription: { endpoint: 'https://push.example.test/sub/old' },
+ waitUntil: (promise: Promise<unknown>) => {
+ completion = promise;
+ },
+ });
+ await completion;
+
+ expect(staleSubscription.unsubscribe).toHaveBeenCalledOnce();
+ expect(pushManager.getSubscription).toHaveBeenCalledOnce();
+ expect(pushManager.subscribe).not.toHaveBeenCalled();
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries subscription sync once after an invalid CSRF token', async () => {
+ const source = await readFile(new URL('../../public/push-sw.js', import.meta.url), 'utf8');
+ const handlers = new Map<string, (event: unknown) => void>();
+ const requests: Array<{ input: string; init?: RequestInit }> = [];
+ const subscription = {
+ endpoint: 'https://push.example.test/sub/retry',
+ options: { applicationServerKey: new Uint8Array([1, 2, 3, 4]).buffer },
+ toJSON: () => ({
+ endpoint: 'https://push.example.test/sub/retry',
+ keys: { p256dh: 'retry-key', auth: 'retry-auth' },
+ }),
+ };
+ let csrfRequests = 0;
+ let subscriptionPosts = 0;
+ const worker = {
+ location: { origin: 'https://avibe.local' },
+ caches: { open: vi.fn() },
+ clients: { matchAll: vi.fn(), openWindow: vi.fn() },
+ registration: { showNotification: vi.fn(), pushManager: { subscribe: vi.fn() } },
+ atob,
+ addEventListener: (type: string, handler: (event: unknown) => void) => handlers.set(type, handler),
+ };
+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {
+ requests.push({ input, init });
+ if (input === '/api/web-push/vapid-public-key') {
+ return Response.json({ public_key: 'AQIDBA' });
+ }
+ if (input === '/api/csrf-token') {
+ csrfRequests += 1;
+ return Response.json({ csrf_token: csrfRequests === 1 ? 'stale-token' : 'fresh-token' });
+ }
+ if (input === '/api/web-push/subscriptions') {
+ subscriptionPosts += 1;
+ if (subscriptionPosts === 1) {
+ return Response.json(
+ { ok: false, message: 'Forbidden: invalid csrf token' },
+ { status: 403 },
+ );
+ }
+ }
+ return Response.json({ ok: true });
+ });
+
+ runInNewContext(source, {
+ self: worker,
+ fetch: fetchMock,
+ navigator: {},
+ URL,
+ Response,
+ Date,
+ Number,
+ JSON,
+ Promise,
+ Uint8Array,
+ });
+
+ let completion: Promise<unknown> | undefined;
+ handlers.get('pushsubscriptionchange')?.({
+ newSubscription: subscription,
+ oldSubscription: { endpoint: 'https://push.example.test/sub/old' },
+ waitUntil: (promise: Promise<unknown>) => {
+ completion = promise;
+ },
+ });
+ await completion;
+
+ expect(csrfRequests).toBe(2);
+ expect(subscriptionPosts).toBe(2);
+ expect(new Headers(requests[2].init?.headers).get('X-Vibe-CSRF-Token')).toBe('stale-token');
+ expect(new Headers(requests[4].init?.headers).get('X-Vibe-CSRF-Token')).toBe('fresh-token');
+ });
});
diff --git a/ui/src/lib/webPush.test.ts b/ui/src/lib/webPush.test.ts
new file mode 100644
index 000000000..fb9746789
--- /dev/null
+++ b/ui/src/lib/webPush.test.ts
@@ -0,0 +1,284 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { ApiContextType } from '@/context/ApiContext';
+import { disableWebPush, enableWebPush, webPushSubscriptionUsesVapidKey } from './webPush';
+
+describe('web push recovery', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('detects a subscription bound to an obsolete VAPID key', () => {
+ vi.stubGlobal('window', {
+ atob: (value: string) => Buffer.from(value, 'base64').toString('binary'),
+ });
+ const subscription = {
+ options: { applicationServerKey: new Uint8Array([1, 2, 3, 4]).buffer },
+ } as PushSubscription;
+
+ expect(webPushSubscriptionUsesVapidKey(subscription, 'AQIDBA')).toBe(true);
+ expect(webPushSubscriptionUsesVapidKey(subscription, 'AQIDBQ')).toBe(false);
+ });
+
+ it('forces a fresh browser subscription while preserving the old endpoint for cleanup', async () => {
+ const oldSubscription = {
+ endpoint: 'https://push.example.test/sub/old',
+ options: { applicationServerKey: new Uint8Array([1, 2, 3, 4]).buffer },
+ unsubscribe: vi.fn(async () => {
+ currentSubscription = null;
+ return true;
+ }),
+ toJSON: () => ({
+ endpoint: 'https://push.example.test/sub/old',
+ keys: { p256dh: 'old-key', auth: 'old-auth' },
+ }),
+ };
+ const newSubscription = {
+ endpoint: 'https://push.example.test/sub/new',
+ options: { applicationServerKey: new Uint8Array([1, 2, 3, 4]).buffer },
+ unsubscribe: vi.fn(),
+ toJSON: () => ({
+ endpoint: 'https://push.example.test/sub/new',
+ keys: { p256dh: 'new-key', auth: 'new-auth' },
+ }),
+ };
+ let currentSubscription: typeof oldSubscription | typeof newSubscription | null = oldSubscription;
+ const registration = {
+ pushManager: {
+ getSubscription: vi.fn(async () => currentSubscription),
+ subscribe: vi.fn(async () => {
+ currentSubscription = newSubscription;
+ return newSubscription;
+ }),
+ },
+ };
+ const localStorage = new Map<string, string>();
+ const endpointCache = {
+ match: vi.fn(async () => undefined),
+ put: vi.fn(async (_url: string, _response: Response) => undefined),
+ };
+ vi.stubGlobal('window', {
+ PushManager: class {},
+ Notification: { requestPermission: vi.fn(async () => 'granted'), permission: 'granted' },
+ crypto: { randomUUID: () => 'device-1' },
+ localStorage: {
+ getItem: (key: string) => localStorage.get(key) ?? null,
+ setItem: (key: string, value: string) => localStorage.set(key, value),
+ },
+ caches: { open: vi.fn(async () => endpointCache) },
+ location: { origin: 'https://avibe.local' },
+ matchMedia: () => ({ matches: false }),
+ atob: (value: string) => Buffer.from(value, 'base64').toString('binary'),
+ });
+ vi.stubGlobal('navigator', {
+ platform: 'MacIntel',
+ maxTouchPoints: 0,
+ userAgent: '',
+ serviceWorker: { register: vi.fn(async () => registration) },
+ });
+ vi.stubGlobal('Notification', window.Notification);
+
+ const api = {
+ getWebPushVapidPublicKey: vi.fn(async () => ({ public_key: 'AQIDBA' })),
+ subscribeWebPush: vi.fn(async () => ({ ok: true })),
+ } as unknown as ApiContextType;
+
+ await enableWebPush(api, { forceResubscribe: true });
+
+ expect(oldSubscription.unsubscribe).toHaveBeenCalledOnce();
+ expect(registration.pushManager.subscribe).toHaveBeenCalledOnce();
+ expect(api.subscribeWebPush).toHaveBeenCalledWith(
+ newSubscription.toJSON(),
+ undefined,
+ 'device-1',
+ ['https://push.example.test/sub/old'],
+ undefined,
+ );
+ expect(endpointCache.put).toHaveBeenCalledWith(
+ 'https://avibe.local/__avibe/web-push-endpoint',
+ expect.any(Response),
+ );
+ const endpointWrite = endpointCache.put.mock.calls.find(
+ ([url]) => url === 'https://avibe.local/__avibe/web-push-endpoint',
+ );
+ expect(endpointWrite).toBeDefined();
+ expect(await endpointWrite![1].json()).toEqual({
+ endpoint: 'https://push.example.test/sub/new',
+ });
+ });
+
+ it('does not re-enable an invalid endpoint when the browser refuses to unsubscribe', async () => {
+ const oldSubscription = {
+ endpoint: 'https://push.example.test/sub/old',
+ options: { applicationServerKey: new Uint8Array([1, 2, 3, 4]).buffer },
+ unsubscribe: vi.fn(async () => false),
+ };
+ const registration = {
+ pushManager: {
+ getSubscription: vi.fn(async () => oldSubscription),
+ subscribe: vi.fn(),
+ },
+ };
+ vi.stubGlobal('window', {
+ PushManager: class {},
+ Notification: { requestPermission: vi.fn(async () => 'granted') },
+ matchMedia: () => ({ matches: false }),
+ atob: (value: string) => Buffer.from(value, 'base64').toString('binary'),
+ });
+ vi.stubGlobal('navigator', {
+ platform: 'MacIntel',
+ maxTouchPoints: 0,
+ userAgent: '',
+ serviceWorker: { register: vi.fn(async () => registration) },
+ });
+ vi.stubGlobal('Notification', window.Notification);
+ const api = {
+ getWebPushVapidPublicKey: vi.fn(async () => ({ public_key: 'AQIDBA' })),
+ subscribeWebPush: vi.fn(),
+ } as unknown as ApiContextType;
+
+ await expect(enableWebPush(api, { forceResubscribe: true })).rejects.toThrow('unsubscribe_failed');
+ expect(oldSubscription.unsubscribe).toHaveBeenCalledOnce();
+ expect(registration.pushManager.subscribe).not.toHaveBeenCalled();
+ expect(api.subscribeWebPush).not.toHaveBeenCalled();
+ });
+
+ it('sends the device ID when disabling a browser subscription', async () => {
+ const subscription = {
+ endpoint: 'https://push.example.test/sub/old',
+ unsubscribe: vi.fn(async () => true),
+ };
+ vi.stubGlobal('window', {
+ localStorage: { getItem: () => 'device-1' },
+ });
+ vi.stubGlobal('navigator', {
+ serviceWorker: {
+ getRegistration: vi.fn(async () => ({
+ pushManager: { getSubscription: vi.fn(async () => subscription) },
+ })),
+ },
+ });
+ const api = {
+ unsubscribeWebPush: vi.fn(async () => ({ ok: true, disabled: true })),
+ } as unknown as ApiContextType;
+
+ expect(await disableWebPush(api)).toBe(true);
+ expect(subscription.unsubscribe).toHaveBeenCalledOnce();
+ expect(api.unsubscribeWebPush).toHaveBeenCalledWith(subscription.endpoint, 'device-1');
+ });
+
+ it('keeps the browser subscription when the server cannot record an opt-out', async () => {
+ const subscription = {
+ endpoint: 'https://push.example.test/sub/old',
+ unsubscribe: vi.fn(async () => true),
+ };
+ vi.stubGlobal('navigator', {
+ serviceWorker: {
+ getRegistration: vi.fn(async () => ({
+ pushManager: { getSubscription: vi.fn(async () => subscription) },
+ })),
+ },
+ });
+ const api = {
+ unsubscribeWebPush: vi.fn(async () => { throw new Error('offline'); }),
+ } as unknown as ApiContextType;
+
+ await expect(disableWebPush(api)).rejects.toThrow('offline');
+ expect(subscription.unsubscribe).not.toHaveBeenCalled();
+ });
+
+ it('recovers the same device and confirmed endpoint after a reload with localStorage blocked', async () => {
+ const entries = new Map<string, Response>();
+ const cache = {
+ match: vi.fn(async (url: string) => entries.get(url)?.clone()),
+ put: vi.fn(async (url: string, response: Response) => {
+ entries.set(url, response.clone());
+ }),
+ };
+ const randomUUID = vi.fn()
+ .mockReturnValueOnce('device-1')
+ .mockReturnValue('unexpected-new-device');
+ let pendingLock = Promise.resolve();
+ const locks = {
+ request: vi.fn((_name: string, callback: () => Promise<string>) => {
+ const result = pendingLock.then(callback);
+ pendingLock = result.then(() => undefined);
+ return result;
+ }),
+ };
+ vi.stubGlobal('window', {
+ localStorage: {
+ getItem: () => { throw new Error('blocked'); },
+ setItem: () => { throw new Error('blocked'); },
+ },
+ caches: { open: vi.fn(async () => cache) },
+ crypto: { randomUUID },
+ location: { origin: 'https://avibe.local' },
+ });
+ vi.stubGlobal('navigator', { locks });
+
+ vi.resetModules();
+ const firstPage = await import('./webPush');
+ vi.resetModules();
+ const secondPage = await import('./webPush');
+ expect(await Promise.all([
+ firstPage.getWebPushDeviceId(),
+ secondPage.getWebPushDeviceId(),
+ ])).toEqual(['device-1', 'device-1']);
+ expect(locks.request).toHaveBeenCalledTimes(2);
+ await firstPage.rememberWebPushEndpoint('https://push.example.test/sub/old');
+
+ vi.resetModules();
+ const nextPage = await import('./webPush');
+ expect(await nextPage.getWebPushDeviceId()).toBe('device-1');
+ expect(await nextPage.getRememberedWebPushEndpoints()).toEqual([
+ 'https://push.example.test/sub/old',
+ ]);
+ expect(randomUUID).toHaveBeenCalledOnce();
+ });
+
+ it('does not re-enable a subscription when conditional recovery is rejected', async () => {
+ const subscription = {
+ endpoint: 'https://push.example.test/sub/new',
+ options: { applicationServerKey: new Uint8Array([1, 2, 3, 4]).buffer },
+ unsubscribe: vi.fn(async () => true),
+ toJSON: () => ({ endpoint: 'https://push.example.test/sub/new' }),
+ };
+ vi.stubGlobal('window', {
+ PushManager: class {},
+ Notification: { requestPermission: vi.fn(async () => 'granted') },
+ localStorage: { getItem: () => null, setItem: vi.fn() },
+ crypto: { randomUUID: () => 'device-1' },
+ matchMedia: () => ({ matches: false }),
+ atob: (value: string) => Buffer.from(value, 'base64').toString('binary'),
+ });
+ vi.stubGlobal('navigator', {
+ platform: 'MacIntel',
+ maxTouchPoints: 0,
+ userAgent: '',
+ serviceWorker: {
+ register: vi.fn(async () => ({
+ pushManager: {
+ getSubscription: vi.fn(async () => null),
+ subscribe: vi.fn(async () => subscription),
+ },
+ })),
+ },
+ });
+ vi.stubGlobal('Notification', window.Notification);
+ const api = {
+ getWebPushVapidPublicKey: vi.fn(async () => ({ public_key: 'AQIDBA' })),
+ subscribeWebPush: vi.fn(async () => ({ ok: true, accepted: false, subscription: null })),
+ } as unknown as ApiContextType;
+
+ await expect(enableWebPush(api, { recoverOnly: true })).rejects.toThrow('recovery_not_authorized');
+ expect(api.subscribeWebPush).toHaveBeenCalledWith(
+ subscription.toJSON(),
+ undefined,
+ 'device-1',
+ [],
+ true,
+ );
+ expect(subscription.unsubscribe).toHaveBeenCalledOnce();
+ });
+});
diff --git a/ui/src/lib/webPush.ts b/ui/src/lib/webPush.ts
index 5c15b4c78..fd950ce81 100644
--- a/ui/src/lib/webPush.ts
+++ b/ui/src/lib/webPush.ts
@@ -3,6 +3,9 @@ import { isIosDevice, isStandalonePwa } from './platform';
const WEB_PUSH_DEVICE_ID_KEY = 'vibe.webPush.deviceId';
const WEB_PUSH_ENDPOINTS_KEY = 'vibe.webPush.endpoints';
+const WEB_PUSH_ENDPOINT_CACHE = 'avibe.web-push-endpoint.v1';
+const WEB_PUSH_ENDPOINT_ENTRY_PATH = '/__avibe/web-push-endpoint';
+const WEB_PUSH_DEVICE_ENTRY_PATH = '/__avibe/web-push-device-id';
export type WebPushSupportState =
| { supported: true; standalone: boolean; requiresStandalone: boolean }
@@ -27,46 +30,84 @@ function arrayBuffersEqual(left: ArrayBuffer | null, right: ArrayBuffer): boolea
return true;
}
-export function getWebPushDeviceId(): string {
+async function readCachedPushValue(path: string, key: 'endpoint' | 'device_id'): Promise<string | null> {
+ if (!('caches' in window)) return null;
try {
- const existing = window.localStorage.getItem(WEB_PUSH_DEVICE_ID_KEY);
- if (existing) return existing;
+ const cache = await window.caches.open(WEB_PUSH_ENDPOINT_CACHE);
+ const response = await cache.match(new URL(path, window.location.origin).href);
+ const payload = response ? await response.json() : null;
+ const value = payload?.[key];
+ return typeof value === 'string' && value ? value : null;
} catch {
- // Storage can be blocked in hardened browsers/WebViews; keep notification
- // controls usable even if the id cannot persist across page loads.
+ return null;
}
- const generated =
- window.crypto?.randomUUID?.() ??
- `device-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
+}
+
+async function writeCachedPushValue(path: string, key: 'endpoint' | 'device_id', value: string): Promise<void> {
+ if (!('caches' in window)) return;
try {
- window.localStorage.setItem(WEB_PUSH_DEVICE_ID_KEY, generated);
+ const cache = await window.caches.open(WEB_PUSH_ENDPOINT_CACHE);
+ await cache.put(new URL(path, window.location.origin).href, new Response(JSON.stringify({ [key]: value }), {
+ headers: { 'content-type': 'application/json' },
+ }));
} catch {
- // Best-effort persistence only.
+ // localStorage remains available where Cache Storage is blocked.
}
- return generated;
}
-export function getRememberedWebPushEndpoints(): string[] {
+let deviceIdPromise: Promise<string> | undefined;
+
+export function getWebPushDeviceId(): Promise<string> {
+ const resolveDeviceId = async () => {
+ let deviceId: string | null = null;
+ try {
+ deviceId = window.localStorage.getItem(WEB_PUSH_DEVICE_ID_KEY);
+ } catch {
+ // Hardened browsers can block localStorage while allowing Cache Storage.
+ }
+ deviceId ||= await readCachedPushValue(WEB_PUSH_DEVICE_ENTRY_PATH, 'device_id');
+ deviceId ||= window.crypto?.randomUUID?.()
+ ?? `device-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
+ try {
+ window.localStorage.setItem(WEB_PUSH_DEVICE_ID_KEY, deviceId);
+ } catch {
+ // Cache Storage or this page's in-memory identity remains available.
+ }
+ await writeCachedPushValue(WEB_PUSH_DEVICE_ENTRY_PATH, 'device_id', deviceId);
+ return deviceId;
+ };
+ deviceIdPromise ??= (async () => (
+ navigator.locks?.request
+ ? navigator.locks.request(WEB_PUSH_DEVICE_ID_KEY, resolveDeviceId)
+ : resolveDeviceId()
+ ))();
+ return deviceIdPromise;
+}
+
+export async function getRememberedWebPushEndpoints(): Promise<string[]> {
+ let localEndpoints: string[] = [];
try {
const raw = window.localStorage.getItem(WEB_PUSH_ENDPOINTS_KEY);
const parsed = raw ? JSON.parse(raw) : [];
if (Array.isArray(parsed)) {
- return parsed.filter((endpoint): endpoint is string => typeof endpoint === 'string' && endpoint.length > 0);
+ localEndpoints = parsed.filter((endpoint): endpoint is string => typeof endpoint === 'string' && endpoint.length > 0);
}
} catch {
- // Best-effort cleanup hints only.
+ // Cache Storage remains available where localStorage is blocked.
}
- return [];
+ const cachedEndpoint = await readCachedPushValue(WEB_PUSH_ENDPOINT_ENTRY_PATH, 'endpoint');
+ return [...new Set([...(cachedEndpoint ? [cachedEndpoint] : []), ...localEndpoints])].slice(0, 8);
}
-export function rememberWebPushEndpoint(endpoint: string | undefined): void {
+export async function rememberWebPushEndpoint(endpoint: string | undefined): Promise<void> {
if (!endpoint) return;
- const endpoints = [endpoint, ...getRememberedWebPushEndpoints().filter((candidate) => candidate !== endpoint)].slice(0, 8);
+ const endpoints = [endpoint, ...(await getRememberedWebPushEndpoints()).filter((candidate) => candidate !== endpoint)].slice(0, 8);
try {
window.localStorage.setItem(WEB_PUSH_ENDPOINTS_KEY, JSON.stringify(endpoints));
} catch {
// Best-effort persistence only.
}
+ await writeCachedPushValue(WEB_PUSH_ENDPOINT_ENTRY_PATH, 'endpoint', endpoint);
}
export function getWebPushSupportState(): WebPushSupportState {
@@ -88,7 +129,29 @@ export async function getExistingWebPushSubscription(): Promise<PushSubscription
return registration?.pushManager.getSubscription() ?? null;
}
-export async function enableWebPush(api: ApiContextType): Promise<PushSubscriptionJSON> {
+export function webPushSubscriptionUsesVapidKey(
+ subscription: PushSubscription,
+ publicKey: string,
+): boolean {
+ try {
+ return arrayBuffersEqual(
+ subscription.options.applicationServerKey,
+ urlBase64ToArrayBuffer(publicKey),
+ );
+ } catch {
+ return false;
+ }
+}
+
+export type EnableWebPushOptions = {
+ forceResubscribe?: boolean;
+ recoverOnly?: boolean;
+};
+
+export async function enableWebPush(
+ api: ApiContextType,
+ options: EnableWebPushOptions = {},
+): Promise<PushSubscriptionJSON> {
const support = getWebPushSupportState();
if (!support.supported) {
throw new Error(support.reason);
@@ -101,10 +164,18 @@ 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)) {
+ let current = existing;
+ if (
+ existing
+ && (options.forceResubscribe
+ || !arrayBuffersEqual(existing.options.applicationServerKey, serverKey))
+ ) {
await existing.unsubscribe();
+ current = await registration.pushManager.getSubscription();
+ if (current?.endpoint === existing.endpoint) {
+ throw new Error('unsubscribe_failed');
+ }
}
- const current = await registration.pushManager.getSubscription();
const subscription =
current ??
(await registration.pushManager.subscribe({
@@ -114,20 +185,33 @@ export async function enableWebPush(api: ApiContextType): Promise<PushSubscripti
const json = subscription.toJSON();
const endpoint = typeof json.endpoint === 'string' ? json.endpoint : undefined;
- await api.subscribeWebPush(json, undefined, getWebPushDeviceId(), getRememberedWebPushEndpoints());
- rememberWebPushEndpoint(endpoint);
+ const previousEndpoints = [
+ ...(existing?.endpoint ? [existing.endpoint] : []),
+ ...await getRememberedWebPushEndpoints(),
+ ];
+ const result = await api.subscribeWebPush(
+ json,
+ undefined,
+ await getWebPushDeviceId(),
+ previousEndpoints,
+ options.recoverOnly,
+ );
+ if (options.recoverOnly && !result.accepted) {
+ await subscription.unsubscribe();
+ throw new Error('recovery_not_authorized');
+ }
+ await rememberWebPushEndpoint(endpoint);
return json;
}
export async function disableWebPush(api: ApiContextType): Promise<boolean> {
const subscription = await getExistingWebPushSubscription();
const endpoint = subscription?.endpoint;
+ if (endpoint) {
+ await api.unsubscribeWebPush(endpoint, await getWebPushDeviceId());
+ }
if (subscription) {
await subscription.unsubscribe();
}
- if (endpoint) {
- await api.unsubscribeWebPush(endpoint);
- return true;
- }
- return false;
+ return Boolean(endpoint);
}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 4e1c5b092..9c192a7a6 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6410,7 +6410,7 @@ def web_push_status():
logger.debug("web push: ignoring invalid status subscription payload", exc_info=True)
subscription_count = web_push_service.count_enabled(conn, user_key=user_key)
current_subscription = (
- web_push_service.get_enabled_by_endpoint(
+ web_push_service.get_by_endpoint(
conn,
endpoint=endpoint,
user_key=user_key,
@@ -6418,13 +6418,20 @@ def web_push_status():
if isinstance(endpoint, str) and endpoint.strip()
else None
)
+ current_subscription_enabled = bool(current_subscription and current_subscription["enabled"])
+ current_subscription_repairable = bool(
+ current_subscription
+ and not current_subscription_enabled
+ and current_subscription.get("provider_invalidated_at")
+ )
return jsonify(
{
"ok": True,
"configured": True,
"public_key": keys.public_key,
"subscription_count": subscription_count,
- "current_subscription_enabled": current_subscription is not None,
+ "current_subscription_enabled": current_subscription_enabled,
+ "current_subscription_repairable": current_subscription_repairable,
"normal_delivery": _web_push_normal_delivery_diagnostics(),
}
)
@@ -6448,21 +6455,31 @@ def web_push_subscribe():
device_id = payload.get("device_id") if isinstance(payload.get("device_id"), str) else None
previous_endpoints = payload.get("previous_endpoints") if isinstance(payload.get("previous_endpoints"), list) else None
subscription = payload.get("subscription") if isinstance(payload.get("subscription"), dict) else payload
+ background_rotation = payload.get("background_rotation") is True
engine = _projects_engine()
try:
with engine.begin() as conn:
- row = web_push_service.upsert_subscription(
- conn,
- user_key=_web_push_user_key(),
- payload=subscription,
- user_agent=user_agent,
- device_label=device_label,
- device_id=device_id,
- previous_endpoints=previous_endpoints,
- )
+ if background_rotation:
+ row = web_push_service.upsert_background_rotated_subscription(
+ conn,
+ user_key=_web_push_user_key(),
+ payload=subscription,
+ user_agent=user_agent,
+ previous_endpoints=previous_endpoints,
+ )
+ else:
+ row = web_push_service.upsert_subscription(
+ conn,
+ user_key=_web_push_user_key(),
+ payload=subscription,
+ user_agent=user_agent,
+ device_label=device_label,
+ device_id=device_id,
+ previous_endpoints=previous_endpoints,
+ )
except ValueError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
- return jsonify({"ok": True, "subscription": row})
+ return jsonify({"ok": True, "accepted": row is not None, "subscription": row})
@app.route("/api/web-push/subscriptions", methods=["DELETE"])
@@ -6471,13 +6488,15 @@ def web_push_unsubscribe():
payload = request.json or {}
endpoint = payload.get("endpoint")
+ device_id = payload.get("device_id") if isinstance(payload.get("device_id"), str) else None
if not isinstance(endpoint, str) or not endpoint.strip():
return jsonify({"ok": False, "error": "endpoint_required"}), 400
engine = _projects_engine()
with engine.begin() as conn:
- disabled = web_push_service.disable_subscription(
+ disabled = web_push_service.disable_device_subscription(
conn,
endpoint=endpoint,
+ device_id=device_id,
user_key=_web_push_user_key(),
)
return jsonify({"ok": True, "disabled": disabled})