Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add browser push notifications for insights and budget warnings (#4705)

Chris Knuteson92a67322938b
diff --git a/Gemfile b/Gemfile
index fcf01e5bd7..bc4345d418 100644
--- a/Gemfile
+++ b/Gemfile
@@ -33,6 +33,9 @@ gem "lookbook", "2.3.11"
gem "hotwire_combobox"
+# Standards-based browser push encryption and VAPID signing
+gem "web-push", "~> 3.1", require: "web_push"
+
# Background Jobs
gem "connection_pool", "~> 2.5" # pin to 2.x; 3.0 breaks sidekiq 8.x
gem "sidekiq"
diff --git a/Gemfile.lock b/Gemfile.lock
index a0bec6c373..17dc31b11c 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -380,7 +380,7 @@ GEM
json-schema (5.2.2)
addressable (~> 2.8)
bigdecimal (~> 3.1)
- jwt (2.10.3)
+ jwt (3.3.0)
base64
language_server-protocol (3.17.0.5)
launchy (3.1.1)
@@ -899,6 +899,9 @@ GEM
activemodel (>= 6.0.0)
bindex (>= 0.4.0)
railties (>= 6.0.0)
+ web-push (3.1.0)
+ jwt (~> 3.0)
+ openssl (>= 3.0)
webauthn (3.4.3)
android_key_attestation (~> 0.3.0)
bindata (~> 2.4)
@@ -1036,6 +1039,7 @@ DEPENDENCIES
vernier
view_component
web-console
+ web-push (~> 3.1)
webauthn (~> 3.4)
webmock
websocket-driver (~> 0.8)
diff --git a/app/controllers/settings/preferences_controller.rb b/app/controllers/settings/preferences_controller.rb
index afe0726424..d760412ffc 100644
--- a/app/controllers/settings/preferences_controller.rb
+++ b/app/controllers/settings/preferences_controller.rb
@@ -5,6 +5,10 @@ class Settings::PreferencesController < ApplicationController
@user = Current.user
@family_members = Current.family.users.where.not(id: @user.id).where(active: true)
@budget_shares = @user.budget_shares_given.index_by(&:viewer_id)
+ if @user.preview_features_enabled?
+ @web_push_public_key = WebPush::Client.vapid[:public_key] if WebPush::Client.configured?
+ @web_push_registrations = @user.web_push_subscriptions.where(session: Current.session).pluck(:id, :endpoint_digest).to_h
+ end
end
# Writes per-user boolean preferences stored in the JSONB `users.preferences`
@@ -13,7 +17,7 @@ class Settings::PreferencesController < ApplicationController
# UsersController#update flow (which expects a full user form payload).
def update
@user = Current.user
- user_params = params.permit(user: [ :preview_features_enabled ]).fetch(:user, {})
+ user_params = params.permit(user: [ :preview_features_enabled, :push_budget_warnings_enabled ]).fetch(:user, {})
preview_changed = false
@user.with_locked_preferences do |updated_prefs|
@@ -22,6 +26,10 @@ class Settings::PreferencesController < ApplicationController
preview_changed = updated_prefs["preview_features_enabled"] != enabled
updated_prefs["preview_features_enabled"] = enabled
end
+ if user_params.key?(:push_budget_warnings_enabled) && updated_prefs["preview_features_enabled"] == true
+ updated_prefs["push_budget_warnings_enabled"] =
+ ActiveModel::Type::Boolean.new.cast(user_params[:push_budget_warnings_enabled])
+ end
end
sync_manual_loans if preview_changed
diff --git a/app/controllers/web_push_subscriptions_controller.rb b/app/controllers/web_push_subscriptions_controller.rb
new file mode 100644
index 0000000000..981f865a5e
--- /dev/null
+++ b/app/controllers/web_push_subscriptions_controller.rb
@@ -0,0 +1,55 @@
+class WebPushSubscriptionsController < ApplicationController
+ before_action :require_browser_push_preview
+ before_action :require_web_push_configuration, only: [ :create, :test_notification ]
+ before_action :set_subscription, only: [ :show, :destroy, :test_notification ]
+
+ rate_limit to: 10, within: 1.minute, by: -> { Current.user.id }, only: :create, name: "web-push-registration",
+ with: -> { render json: { error: t("web_push.errors.rate_limited") }, status: :too_many_requests }
+ rate_limit to: 2, within: 1.minute, by: -> { Current.user.id }, only: :test_notification, name: "web-push-test",
+ with: -> { render json: { error: t("web_push.errors.rate_limited") }, status: :too_many_requests }
+
+ def create
+ attributes = params.permit(:endpoint, :p256dh, :auth)
+ subscription = WebPushSubscription.register_for!(user: Current.user, session: Current.session,
+ endpoint: attributes[:endpoint], p256dh: attributes[:p256dh], auth: attributes[:auth])
+ render json: { id: subscription.id }, status: :created
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
+ render json: { error: t("web_push.errors.registration") }, status: :unprocessable_entity
+ end
+
+ def show
+ delivery = @subscription.push_deliveries.where(insight_id: nil).order(created_at: :desc).first
+ render json: { id: @subscription.id, test_status: delivery&.status }
+ end
+
+ def destroy
+ @subscription.destroy!
+ head :no_content
+ end
+
+ def test_notification
+ delivery = @subscription.request_test_notification!
+ return render json: { error: t("web_push.errors.rate_limited") }, status: :too_many_requests unless delivery
+
+ if delivery.enqueue!
+ render json: { status: "queued" }, status: :accepted
+ else
+ render json: { error: t("web_push.errors.enqueue") }, status: :service_unavailable
+ end
+ end
+
+ private
+ def require_browser_push_preview
+ unless Current.user.preview_features_enabled? && Current.session.user_id == Current.user.id
+ render json: { error: t("web_push.errors.preview") }, status: :forbidden
+ end
+ end
+
+ def require_web_push_configuration
+ render json: { error: t("web_push.errors.unconfigured") }, status: :service_unavailable unless WebPush::Client.configured?
+ end
+
+ def set_subscription
+ @subscription = Current.user.web_push_subscriptions.where(session: Current.session).find(params[:id])
+ end
+end
diff --git a/app/javascript/controllers/web_push_controller.js b/app/javascript/controllers/web_push_controller.js
new file mode 100644
index 0000000000..7d0373b1e7
--- /dev/null
+++ b/app/javascript/controllers/web_push_controller.js
@@ -0,0 +1,232 @@
+import { Controller } from "@hotwired/stimulus";
+
+export default class extends Controller {
+ static targets = ["status", "enable", "disable", "test", "iosGuidance"];
+ static values = {
+ publicKey: String,
+ subscriptionId: String,
+ registrations: Object,
+ url: String,
+ messages: Object,
+ };
+
+ async connect() {
+ this.lifecycleGeneration = (this.lifecycleGeneration || 0) + 1;
+ const generation = this.lifecycleGeneration;
+ const isCurrent = () => generation === this.lifecycleGeneration;
+ this.pollGeneration = (this.pollGeneration || 0) + 1;
+ this.busy = true;
+ this.subscriptionIdValue = "";
+ this.supported = window.isSecureContext && "serviceWorker" in navigator &&
+ "PushManager" in window && "Notification" in window;
+ const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) ||
+ (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
+ const standalone = window.matchMedia("(display-mode: standalone)").matches || navigator.standalone;
+ this.iosGuidanceTarget.classList.toggle("hidden", !ios || standalone);
+ if (!this.supported || (ios && !standalone)) {
+ this.supported = false;
+ this.setStatus("unsupported");
+ } else {
+ try {
+ const registration = await navigator.serviceWorker.getRegistration("/") ||
+ await navigator.serviceWorker.register("/service-worker");
+ if (!isCurrent()) return;
+ const subscription = await registration.pushManager.getSubscription();
+ if (!isCurrent()) return;
+ this.registration = registration;
+ this.subscription = subscription;
+ if (this.subscription) {
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(this.subscription.endpoint));
+ if (!isCurrent()) return;
+ const digest = Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
+ this.subscriptionIdValue = Object.entries(this.registrationsValue)
+ .find(([, registeredDigest]) => registeredDigest === digest)?.[0] || "";
+ }
+ this.setStatus(!this.publicKeyValue ? "unconfigured" :
+ Notification.permission === "denied" ? "denied" :
+ this.subscriptionIdValue && this.subscriptionUsesCurrentKey(this.subscription) ? "enabled" : "disabled");
+ } catch {
+ if (isCurrent()) this.setStatus("request");
+ }
+ }
+ if (!isCurrent()) return;
+ this.busy = false;
+ this.updateControls();
+ }
+
+ disconnect() {
+ this.lifecycleGeneration++;
+ this.stopPolling();
+ }
+
+ async enable() {
+ await this.run(async (isCurrent) => {
+ // Request permission before awaiting any other work: Safari requires the
+ // permission request to retain this button's direct user activation.
+ const permission = Notification.permission === "granted" ? "granted" :
+ await Notification.requestPermission();
+ if (!isCurrent()) return;
+ if (permission !== "granted") {
+ this.setStatus(permission === "denied" ? "denied" : "permission");
+ return;
+ }
+ await navigator.serviceWorker.ready;
+ if (!isCurrent()) return;
+ const currentSubscription = await this.registration.pushManager.getSubscription();
+ if (!isCurrent()) return;
+ this.subscription = currentSubscription;
+ if (this.subscription && !this.subscriptionUsesCurrentKey(this.subscription)) {
+ if (this.subscriptionIdValue) await this.request(this.deviceUrl(), "DELETE");
+ if (!isCurrent()) return;
+ this.subscriptionIdValue = "";
+ const unsubscribed = await this.subscription.unsubscribe();
+ if (!isCurrent()) return;
+ if (!unsubscribed) throw new Error("Browser subscription replacement failed");
+ this.subscription = null;
+ }
+ const browserSubscription = this.subscription || await this.registration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: this.applicationServerKey(),
+ });
+ if (!isCurrent()) return;
+ this.subscription = browserSubscription;
+ const subscription = this.subscription.toJSON();
+ const result = await this.request(this.urlValue, "POST", {
+ endpoint: subscription.endpoint,
+ p256dh: subscription.keys.p256dh,
+ auth: subscription.keys.auth,
+ });
+ if (!isCurrent()) return;
+ this.subscriptionIdValue = result.id;
+ this.setStatus("enabled");
+ });
+ }
+
+ async disable() {
+ await this.run(async (isCurrent) => {
+ this.stopPolling();
+ if (this.subscriptionIdValue) await this.request(this.deviceUrl(), "DELETE");
+ if (!isCurrent()) return;
+ this.subscriptionIdValue = "";
+ if (this.subscription) await this.subscription.unsubscribe();
+ if (!isCurrent()) return;
+ this.subscription = null;
+ this.setStatus("disabled");
+ });
+ }
+
+ async test() {
+ await this.run(async (isCurrent) => {
+ this.stopPolling();
+ await this.request(`${this.deviceUrl()}/test_notification`, "POST");
+ if (!isCurrent()) return;
+ this.setStatus("queued");
+ this.pollCount = 0;
+ this.pollTimer = setTimeout(() => this.pollTest(), 1500);
+ });
+ }
+
+ async pollTest() {
+ const generation = this.pollGeneration;
+ try {
+ const result = await this.request(this.deviceUrl(), "GET");
+ if (generation !== this.pollGeneration) return;
+ const status = result.test_status || "pending";
+ this.setStatus(status);
+ if (status === "pending" && ++this.pollCount < 20) {
+ this.pollTimer = setTimeout(() => this.pollTest(), 1500);
+ } else if (status === "pending") {
+ this.setStatus("expired");
+ }
+ } catch (error) {
+ if (generation !== this.pollGeneration) return;
+ this.showError(error);
+ }
+ }
+
+ async run(action) {
+ if (this.busy) return;
+ const generation = this.lifecycleGeneration;
+ const isCurrent = () => generation === this.lifecycleGeneration;
+ this.busy = true;
+ this.updateControls();
+ try {
+ await action(isCurrent);
+ } catch (error) {
+ if (isCurrent()) this.showError(error);
+ } finally {
+ if (isCurrent()) {
+ this.busy = false;
+ this.updateControls();
+ }
+ }
+ }
+
+ async request(url, method, body) {
+ const response = await fetch(url, {
+ method,
+ credentials: "same-origin",
+ redirect: "error",
+ headers: {
+ Accept: "application/json",
+ "Content-Type": "application/json",
+ "X-CSRF-Token": document.querySelector("meta[name='csrf-token']")?.content || "",
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ if (response.status === 204) return {};
+ if (response.status === 404 && method === "DELETE") return {};
+ const result = await response.json();
+ if (!response.ok) {
+ const error = new Error("Browser notification request failed");
+ error.status = response.status;
+ error.userMessage = result.error || this.messagesValue.request;
+ throw error;
+ }
+ return result;
+ }
+
+ showError(error) {
+ if (error.status === 404) {
+ this.subscriptionIdValue = "";
+ this.updateControls();
+ }
+ this.statusTarget.textContent = error.userMessage || this.messagesValue.request;
+ }
+
+ subscriptionUsesCurrentKey(subscription) {
+ const boundKey = subscription?.options?.applicationServerKey;
+ if (!boundKey || !this.publicKeyValue) return false;
+ const expected = this.applicationServerKey();
+ const actual = new Uint8Array(boundKey);
+ return actual.length === expected.length && expected.every((byte, index) => byte === actual[index]);
+ }
+
+ applicationServerKey() {
+ const encoded = this.publicKeyValue.replace(/-/g, "+").replace(/_/g, "/");
+ const decoded = atob(encoded.padEnd(Math.ceil(encoded.length / 4) * 4, "="));
+ return Uint8Array.from(decoded, (character) => character.charCodeAt(0));
+ }
+
+ deviceUrl() {
+ return `${this.urlValue}/${this.subscriptionIdValue}`;
+ }
+
+ setStatus(key) {
+ this.statusTarget.textContent = this.messagesValue[key] || this.messagesValue.request;
+ }
+
+ stopPolling() {
+ this.pollGeneration++;
+ clearTimeout(this.pollTimer);
+ }
+
+ updateControls() {
+ const available = Boolean(this.supported && this.publicKeyValue && this.registration);
+ const registered = Boolean(this.subscriptionIdValue && this.subscription);
+ const enabled = registered && this.subscriptionUsesCurrentKey(this.subscription);
+ this.enableTarget.disabled = this.busy || !available || enabled;
+ this.disableTarget.disabled = this.busy || !registered;
+ this.testTarget.disabled = this.busy || !available || !enabled;
+ }
+}
diff --git a/app/jobs/deliver_insight_notification_job.rb b/app/jobs/deliver_insight_notification_job.rb
index f6793e7aa3..ad6c171d70 100644
--- a/app/jobs/deliver_insight_notification_job.rb
+++ b/app/jobs/deliver_insight_notification_job.rb
@@ -1,44 +1,44 @@
# frozen_string_literal: true
+# Delivers one PushDelivery row through its channel's #deliver adapter.
class DeliverInsightNotificationJob < ApplicationJob
- queue_as :scheduled
+ queue_as :high_priority
+ # The persisted delivery owns the total budget; ActiveJob only schedules
+ # backoff. Sidekiq must not start a separate retry chain.
+ sidekiq_options retry: false
- retry_on Apns::Client::TransientError, wait: :polynomially_longer, attempts: 5
+ retry_on PushDelivery::TransientError, wait: :polynomially_longer, attempts: PushDelivery::MAX_PROVIDER_ATTEMPTS
discard_on ActiveRecord::RecordNotFound
- def self.enqueue_for(insight)
- return unless Apns::Client.available? && insight.priority_high? && insight.active?
-
- insight.family.users.includes(:push_subscriptions).find_each do |user|
- next unless user.active? && user.preview_features_enabled?
-
- user.push_subscriptions.recent.find_each do |subscription|
- perform_later(insight_id: insight.id, push_subscription_id: subscription.id)
- end
- end
- end
-
- def perform(insight_id:, push_subscription_id:)
- return unless Apns::Client.available?
-
- insight = Insight.find(insight_id)
- subscription = PushSubscription.find(push_subscription_id)
- return unless subscription.user.family_id == insight.family_id
- return unless subscription.eligible? && subscription.user.preview_features_enabled?
- return unless insight.priority_high? && insight.active?
- # The account it names may have stopped being shared with everyone
- # since the insight was generated; the feed hides it, so no push either.
- return unless Insight.about_shared_accounts.exists?(insight.id)
-
- PushSubscription::Delivery.new(subscription).call do |client|
- I18n.with_locale(insight.family.locale) do
- client.deliver(
- token: subscription.token,
- title: I18n.t("insights.notification.title"),
- body: I18n.t("insights.notification.body"),
- insight_id: insight.id
- )
+ def perform(push_delivery_id: nil, insight_id: nil, push_subscription_id: nil)
+ delivery =
+ if push_delivery_id
+ PushDelivery.find(push_delivery_id)
+ else
+ # Queued before the ledger existed. Synthesize the row this send needs
+ # so in-flight jobs survive the deploy instead of dying on an
+ # incompatible signature; the claim re-checks every eligibility rule.
+ subscription = PushSubscription.find(push_subscription_id)
+ insight = Insight.find(insight_id)
+ PushDelivery.for_subscription(subscription, insight)
end
+ return unless delivery
+
+ attempt = delivery.claim_attempt!
+ return unless attempt
+
+ subscription = delivery.subscription
+ subscription_updated_at = subscription.updated_at
+ result = subscription.deliver(delivery)
+ if result == :skipped
+ # The channel could not attempt (for example the client went unavailable
+ # between claim and deliver); release the reservation instead of
+ # recording an outcome the provider never gave.
+ delivery.release_attempt!(attempt)
+ else
+ delivery.complete_attempt!(attempt, result: result, subscription_updated_at: subscription_updated_at)
end
+ rescue PushDelivery::TransientError
+ raise if delivery.retry_attempt!(attempt)
end
end
diff --git a/app/jobs/generate_insights_job.rb b/app/jobs/generate_insights_job.rb
index fa5d72d93f..b7546b9781 100644
--- a/app/jobs/generate_insights_job.rb
+++ b/app/jobs/generate_insights_job.rb
@@ -40,12 +40,11 @@ class GenerateInsightsJob < ApplicationJob
# broadcast below too, not just the generation.
return unless family.preview_features_enabled?
- notifiable_insights = with_advisory_lock(family_id) do
+ with_advisory_lock(family_id) do
I18n.with_locale(family.locale) do
result = Insight::GeneratorRegistry.new(family).generate_all
- created_or_resurfaced = upsert_insights(family, result.insights)
+ upsert_insights(family, result.insights)
expire_stale_insights(family, result)
- created_or_resurfaced
end
end
@@ -53,7 +52,6 @@ class GenerateInsightsJob < ApplicationJob
# current state, so a subscribed /insights page (waiting on its manual
# refresh) always gets its list and button restored.
I18n.with_locale(family.locale) { broadcast_feed(family) }
- Array(notifiable_insights).each { |insight| DeliverInsightNotificationJob.enqueue_for(insight) }
end
def broadcast_feed(family)
@@ -137,6 +135,7 @@ class GenerateInsightsJob < ApplicationJob
body: writer.write(generated),
metadata: metadata,
facts: facts,
+ notification_version: existing.notification_version + 1,
period_start: generated.period_start,
period_end: generated.period_end,
generated_at: Time.current,
@@ -149,7 +148,7 @@ class GenerateInsightsJob < ApplicationJob
# numbers. Expiry was the system's doing, not the user's, so the
# insight resurfaces, with the body filled from the current facts.
existing.update!(title: generated.title, body: writer.write(generated), status: "active", facts: facts,
- generated_at: Time.current, read_at: nil)
+ notification_version: existing.notification_version + 1, generated_at: Time.current, read_at: nil)
existing
else
# Same signal, same numbers: don't undo the user's read/dismissed
diff --git a/app/jobs/recover_push_deliveries_job.rb b/app/jobs/recover_push_deliveries_job.rb
new file mode 100644
index 0000000000..e841fff26a
--- /dev/null
+++ b/app/jobs/recover_push_deliveries_job.rb
@@ -0,0 +1,11 @@
+# The push ledger's outbox sweep. Runs on its own schedule so a failed enqueue
+# or an abandoned claim waits one PushDelivery::CLAIM_TIMEOUT, not until the
+# next insight generation.
+class RecoverPushDeliveriesJob < ApplicationJob
+ queue_as :scheduled
+ sidekiq_options lock: :until_executed, on_conflict: :log
+
+ def perform
+ PushDelivery.recoverable.find_each(&:recover!)
+ end
+end
diff --git a/app/models/insight.rb b/app/models/insight.rb
index c33dfd0645..9e26b22af6 100644
--- a/app/models/insight.rb
+++ b/app/models/insight.rb
@@ -16,6 +16,13 @@
# migration — only the vocabulary the code and the UI speak was wrong.
class Insight < ApplicationRecord
belongs_to :family
+ has_many :push_deliveries, dependent: :destroy
+
+ # A new insight, or a new notification_version (GenerateInsightsJob bumps it
+ # when the signal materially changes), is one event for push recipients. They
+ # are recorded in the save's transaction and enqueued once it commits.
+ after_save -> { PushDelivery.record_for_insight!(self) }, if: :new_notification_version?
+ after_commit -> { PushDelivery.enqueue_insight_deliveries(self) }, on: [ :create, :update ], if: :new_notification_version?
TYPES = %w[
spending_anomaly
@@ -106,6 +113,16 @@ class Insight < ApplicationRecord
.order(generated_at: :desc)
}
+ # The one push policy, read by every channel: high-priority insights, plus
+ # near-limit (medium) budget warnings for users who opt in. Tenancy and
+ # shared-account visibility mirror the feed.
+ def notifies?(user)
+ return false unless active? && user.active? && user.family_id == family_id && user.preview_features_enabled?
+ return false unless priority_high? || (insight_type == "budget_at_risk" && priority_medium? && user.push_budget_warnings_enabled?)
+
+ Insight.about_shared_accounts.exists?(id)
+ end
+
def mark_read!
return unless active?
@@ -127,4 +144,9 @@ class Insight < ApplicationRecord
update!(status: :read, dismissed_at: nil, read_at: read_at || Time.current)
end
+
+ private
+ def new_notification_version?
+ previously_new_record? || saved_change_to_notification_version?
+ end
end
diff --git a/app/models/push_delivery.rb b/app/models/push_delivery.rb
new file mode 100644
index 0000000000..06c4269d0d
--- /dev/null
+++ b/app/models/push_delivery.rb
@@ -0,0 +1,200 @@
+# One delivery ledger for every push channel. A row is the durable record of
+# "this subscription was a recipient of this insight version": created at the
+# event, claimed before provider IO, completed with the provider outcome. The
+# channel only decides how a payload is built and how a delivery call reports
+# back; the idempotency, attempt budget and recovery live here. (Rule email
+# deliveries keep their own NotificationDelivery ledger; their dedup domain is
+# a rule matched against a transaction, not an insight version.)
+class PushDelivery < ApplicationRecord
+ belongs_to :subscription, polymorphic: true
+ belongs_to :insight, optional: true
+
+ enum :status, { pending: "pending", accepted: "accepted", skipped: "skipped",
+ rejected: "rejected", failed: "failed", enqueue_failed: "enqueue_failed" }, prefix: true
+
+ TEST_SEND_WINDOW = 15.minutes
+ CLAIM_TIMEOUT = 15.minutes
+ MAX_PROVIDER_ATTEMPTS = 5
+
+ # A channel is a subscription model with .channel_ready?, #eligible? (the
+ # device can still receive) and #deliver(delivery), which returns a result
+ # symbol or raises TransientError. Adding a channel means adding its model here.
+ CHANNELS = %w[PushSubscription WebPushSubscription].freeze
+
+ class TransientError < StandardError; end
+
+ scope :apns, -> { where(subscription_type: "PushSubscription") }
+ scope :web_push, -> { where(subscription_type: "WebPushSubscription") }
+
+ # Called inside the insight version's transaction. Recipient eligibility is
+ # captured at the event, so later registration or opt-in cannot add a backlog.
+ def self.record_for_insight!(insight)
+ return unless insight.active?
+
+ CHANNELS.map(&:constantize).select(&:channel_ready?).each do |channel|
+ channel.joins(:user).where(users: { family_id: insight.family_id, active: true })
+ .includes(:user).find_each do |subscription|
+ for_subscription(subscription, insight) if subscription.eligible? && insight.notifies?(subscription.user)
+ end
+ end
+ end
+
+ def self.for_subscription(subscription, insight)
+ transaction do
+ # The device can disappear after event-time eligibility was read. Lock
+ # the parent before inserting its ledger row so deletion cannot race it.
+ locked = subscription.class.lock.find_by(id: subscription.id)
+ next unless locked
+ create_or_find_by!(subscription: locked, insight: insight,
+ insight_version: insight.notification_version)
+ end
+ end
+
+ # Every channel enqueues from the same event: unclaimed pending rows and rows
+ # whose enqueue failed get one claim each.
+ def self.enqueue_insight_deliveries(insight)
+ deliveries = where(insight: insight, insight_version: insight.notification_version)
+ deliveries.where(status: :enqueue_failed)
+ .or(deliveries.where(status: :pending, enqueued_at: nil))
+ .find_each do |delivery|
+ delivery.enqueue! if delivery.eligible?
+ end
+ end
+
+ # Swept by RecoverPushDeliveriesJob every CLAIM_TIMEOUT: failed enqueues and
+ # abandoned claims are retried; terminal provider outcomes stay put.
+ scope :recoverable, -> {
+ where(status: :enqueue_failed).or(
+ where(status: :pending).where("enqueued_at IS NULL OR enqueued_at < ?", CLAIM_TIMEOUT.ago)
+ )
+ }
+
+ def recover!
+ if eligible?
+ enqueue!(recover: true)
+ else
+ with_lock { update!(status: :skipped) if status_pending? || status_enqueue_failed? }
+ end
+ end
+
+ def enqueue!(recover: false)
+ return false unless channel_ready?
+
+ claimed_at = Time.current
+ claimed = with_lock do
+ claim_available = enqueued_at.nil? || (recover && enqueued_at < CLAIM_TIMEOUT.ago)
+ next false unless status_enqueue_failed? || (status_pending? && claim_available)
+ next false if attempted_at && attempted_at > CLAIM_TIMEOUT.ago
+ if provider_attempts >= MAX_PROVIDER_ATTEMPTS
+ update!(status: :failed)
+ next false
+ end
+ update!(status: :pending, enqueued_at: claimed_at)
+ true
+ end
+ return false unless claimed
+
+ job = DeliverInsightNotificationJob.perform_later(push_delivery_id: id)
+ return true if job
+ mark_enqueue_failed!(claimed_at)
+ false
+ rescue ActiveJob::EnqueueError, Redis::BaseError, RedisClient::Error
+ mark_enqueue_failed!(claimed_at)
+ false
+ end
+
+ # The reservation commits before provider IO. A lost worker therefore spends
+ # an attempt, and a recovered ActiveJob cannot start a fresh provider budget.
+ def claim_attempt!
+ return unless channel_ready?
+
+ with_lock do
+ next unless status_pending?
+ next if attempted_at && attempted_at > CLAIM_TIMEOUT.ago
+ unless eligible?
+ update!(status: :skipped)
+ next
+ end
+ if provider_attempts >= MAX_PROVIDER_ATTEMPTS
+ update!(status: :failed)
+ next
+ end
+ update!(provider_attempts: provider_attempts + 1, attempted_at: Time.current)
+ provider_attempts
+ end
+ end
+
+ def retry_attempt!(attempt)
+ with_lock do
+ next false unless current_attempt?(attempt)
+ update!(attempted_at: nil, status: provider_attempts >= MAX_PROVIDER_ATTEMPTS ? :failed : :pending)
+ status_pending?
+ end
+ end
+
+ # The channel could not attempt (for example the client went unavailable
+ # between claim and deliver). Hand back the whole reservation so an outage
+ # cannot exhaust the budget without provider IO, and clear the queue claim
+ # so the next recovery sweep can re-enqueue it.
+ def release_attempt!(attempt)
+ with_lock do
+ next false unless current_attempt?(attempt)
+ update!(attempted_at: nil, enqueued_at: nil, provider_attempts: provider_attempts - 1)
+ true
+ end
+ end
+
+ def complete_attempt!(attempt, result:, subscription_updated_at: nil)
+ if result == :gone
+ # Registration takes parent then child locks. Cleanup uses that same
+ # order, and never holds either lock while contacting the provider.
+ self.class.transaction do
+ subscription = subscription_type.constantize.lock.find_by(id: subscription_id)
+ next unless subscription
+ with_lock do
+ next unless current_attempt?(attempt)
+ if subscription.updated_at == subscription_updated_at
+ subscription.destroy!
+ else
+ update!(status: :rejected, attempted_at: nil)
+ end
+ end
+ end
+ else
+ with_lock do
+ next unless current_attempt?(attempt)
+ status = case result
+ when :accepted then :accepted
+ when :failed then :failed
+ else :rejected
+ end
+ update!(status: status, attempted_at: nil)
+ end
+ end
+ end
+
+ def eligible?
+ return false unless subscription&.eligible?
+
+ if insight
+ insight.notification_version == insight_version && insight.notifies?(subscription.user)
+ else
+ # Diagnostic test sends expire quickly.
+ subscription.user.preview_features_enabled? && created_at > TEST_SEND_WINDOW.ago
+ end
+ end
+
+ private
+ def channel_ready?
+ subscription.present? && subscription.class.channel_ready?
+ end
+
+ def current_attempt?(attempt)
+ status_pending? && provider_attempts == attempt
+ end
+
+ def mark_enqueue_failed!(claimed_at)
+ self.class.where(id: id, status: :pending, enqueued_at: claimed_at, attempted_at: nil)
+ .update_all(status: :enqueue_failed, updated_at: Time.current)
+ end
+end
diff --git a/app/models/push_subscription.rb b/app/models/push_subscription.rb
index 38a7af887e..1acf6a2705 100644
--- a/app/models/push_subscription.rb
+++ b/app/models/push_subscription.rb
@@ -2,6 +2,7 @@ require "digest"
class PushSubscription < ApplicationRecord
belongs_to :user
+ has_many :push_deliveries, as: :subscription, dependent: :destroy
enum :environment, { sandbox: "sandbox", production: "production" }, validate: true
@@ -58,8 +59,26 @@ class PushSubscription < ApplicationRecord
user.active? && last_registered_at > 90.days.ago
end
+ def self.channel_ready?
+ Apns::Client.available?
+ end
+
+ # The APNs adapter for PushDelivery.
+ def deliver(delivery)
+ PushSubscription::Delivery.new(self).call do |client|
+ I18n.with_locale(user.family.locale) do
+ client.deliver(token: token, title: I18n.t("insights.notification.title"),
+ body: I18n.t("insights.notification.body"), insight_id: delivery.insight_id)
+ end
+ end
+ rescue Apns::Client::TransientError => e
+ raise PushDelivery::TransientError, e.message
+ end
+
# A response may arrive after the app has registered again. Only remove the
# exact registration sent, and respect APNs' invalidation timestamp when given.
+ # Destroy (not delete) so the subscription's ledger rows are cleaned up with
+ # it; a surviving row would claim against a parent that no longer exists.
def invalidate_if_unchanged!(response)
return unless response.status.to_i == 410
@@ -70,6 +89,6 @@ class PushSubscription < ApplicationRecord
end
self.class.where(id: id, token: token, environment: environment,
- last_registered_at: last_registered_at).delete_all
+ last_registered_at: last_registered_at).destroy_all
end
end
diff --git a/app/models/session.rb b/app/models/session.rb
index 6ca442a730..a5f5bc4e9d 100644
--- a/app/models/session.rb
+++ b/app/models/session.rb
@@ -23,6 +23,7 @@ class Session < ApplicationRecord
SESSION_TOUCH_INTERVAL = 1.hour
belongs_to :user, counter_cache: :sessions_count
+ has_many :web_push_subscriptions, dependent: :destroy
belongs_to :active_impersonator_session,
-> { where(status: :in_progress) },
class_name: "ImpersonationSession",
diff --git a/app/models/user.rb b/app/models/user.rb
index a53ad93cfb..6435686581 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -28,6 +28,7 @@ class User < ApplicationRecord
has_many :chats, dependent: :destroy
has_many :api_keys, dependent: :destroy
has_many :push_subscriptions, dependent: :destroy
+ has_many :web_push_subscriptions, dependent: :destroy
has_many :webauthn_credentials, dependent: :destroy
has_many :mobile_devices, dependent: :destroy
has_many :invitations, foreign_key: :inviter_id, dependent: :destroy
@@ -980,6 +981,10 @@ class User < ApplicationRecord
preferences&.dig("disable_modal_click_outside") == true
end
+ def push_budget_warnings_enabled?
+ preferences&.dig("push_budget_warnings_enabled") == true
+ end
+
def preview_features_enabled?
preferences&.dig("preview_features_enabled") == true
end
diff --git a/app/models/web_push/client.rb b/app/models/web_push/client.rb
new file mode 100644
index 0000000000..431bc7c22b
--- /dev/null
+++ b/app/models/web_push/client.rb
@@ -0,0 +1,48 @@
+require "web_push"
+
+# The maintained web-push library owns RFC 8291 encryption and VAPID signing.
+# This boundary only validates destinations and classifies sanitized outcomes.
+class WebPush::Client
+ class TransientError < StandardError; end
+
+ def self.vapid
+ {
+ public_key: ENV["WEB_PUSH_VAPID_PUBLIC_KEY"],
+ private_key: ENV["WEB_PUSH_VAPID_PRIVATE_KEY"],
+ subject: ENV["WEB_PUSH_VAPID_SUBJECT"]
+ }
+ end
+
+ def self.configured?
+ values = vapid
+ return false unless values.values.all?(&:present?)
+ subject = URI.parse(values[:subject])
+ contact_email = subject.is_a?(URI::MailTo) && subject.to.to_s.match?(URI::MailTo::EMAIL_REGEXP)
+ contact_url = subject.is_a?(URI::HTTPS) && subject.host.present? && subject.userinfo.nil?
+ return false unless contact_email || contact_url
+ WebPush::VapidKey.from_keys(values[:public_key], values[:private_key]).curve.check_key
+ rescue URI::Error, OpenSSL::OpenSSLError, ArgumentError
+ false
+ end
+
+ def deliver(subscription:, payload:)
+ return :rejected unless WebPushSubscription.allowed_endpoint?(subscription.endpoint)
+
+ WebPush.payload_send(
+ endpoint: subscription.endpoint, p256dh: subscription.p256dh, auth: subscription.auth,
+ message: payload.to_json, vapid: self.class.vapid,
+ ttl: 300, urgency: "normal", open_timeout: 5, read_timeout: 10, ssl_timeout: 5
+ )
+ :accepted
+ rescue WebPush::InvalidSubscription, WebPush::ExpiredSubscription
+ :gone
+ rescue WebPush::TooManyRequests, WebPush::PushServiceError,
+ Net::OpenTimeout, Net::ReadTimeout, Net::HTTPBadResponse, Timeout::Error,
+ OpenSSL::SSL::SSLError, SocketError, IOError, SystemCallError
+ # Provider exceptions include response bodies, and connection errors may
+ # contain the endpoint. Neither belongs in Rails or Sidekiq retry logs.
+ raise TransientError, "Browser push delivery temporarily unavailable", cause: nil
+ rescue WebPush::Error, OpenSSL::OpenSSLError, ArgumentError
+ :rejected
+ end
+end
diff --git a/app/models/web_push_subscription.rb b/app/models/web_push_subscription.rb
new file mode 100644
index 0000000000..7832daea3c
--- /dev/null
+++ b/app/models/web_push_subscription.rb
@@ -0,0 +1,177 @@
+require "base64"
+require "digest"
+require "openssl"
+require "uri"
+
+# Browser subscriptions have a separate lifecycle and credentials from native APNs.
+class WebPushSubscription < ApplicationRecord
+ include Encryptable
+
+ MAX_SUBSCRIPTIONS_PER_USER = 20
+ TEST_NOTIFICATION_COOLDOWN = 30.seconds
+
+ belongs_to :user
+ belongs_to :session
+ has_many :push_deliveries, as: :subscription, dependent: :destroy
+
+ if encryption_ready?
+ encrypts :endpoint, :p256dh, :auth
+ end
+
+ before_validation :set_endpoint_digest
+ validates :endpoint, presence: true, length: { maximum: 4096 }
+ validates :endpoint_digest, presence: true
+ validates :p256dh, presence: true, length: { maximum: 88 }
+ validates :auth, presence: true, length: { maximum: 24 }
+ validate :validate_destination
+ validate :validate_keys
+ validate :validate_session_owner
+
+ # An endpoint alone is not ownership proof. Moving a browser between accounts
+ # or sessions requires both original subscription keys and gets a new row ID,
+ # so queued sends and delayed deletes cannot target the replacement.
+ def self.register_for!(user:, session:, endpoint:, p256dh:, auth:)
+ candidate = new(user: user, session: session, endpoint: endpoint, p256dh: p256dh, auth: auth)
+ candidate.validate!
+
+ attempts = 0
+ begin
+ user.with_lock do
+ transaction(requires_new: true) do
+ existing = lock.find_by(endpoint_digest: candidate.endpoint_digest)
+ if existing&.user_id != user.id && user.web_push_subscriptions.count >= MAX_SUBSCRIPTIONS_PER_USER
+ candidate.errors.add(:base, :invalid)
+ raise ActiveRecord::RecordInvalid, candidate
+ end
+ if existing && (existing.user_id != user.id || existing.session_id != session.id)
+ unless existing.matches_keys?(p256dh, auth)
+ candidate.errors.add(:base, :taken)
+ raise ActiveRecord::RecordInvalid, candidate
+ end
+ existing.destroy!
+ existing = nil
+ end
+ registration = existing || candidate
+ registration.assign_attributes(p256dh: p256dh, auth: auth)
+ registration.save!
+ registration
+ end
+ end
+ rescue ActiveRecord::RecordNotUnique
+ attempts += 1
+ retry if attempts < 2
+ raise
+ end
+ end
+
+ def self.allowed_endpoint?(endpoint)
+ return false unless endpoint.is_a?(String) && endpoint.bytesize <= 4096
+ return false unless endpoint.ascii_only? && !endpoint.match?(/[\s\\]/)
+
+ uri = URI.parse(endpoint)
+ return false unless uri.is_a?(URI::HTTPS) && uri.port == 443 && uri.userinfo.nil? && uri.fragment.nil?
+
+ host = uri.host.to_s.downcase
+ host == "fcm.googleapis.com" || host == "updates.push.services.mozilla.com" ||
+ host.match?(/\A[a-z0-9-]+(?:\.[a-z0-9-]+)*\.push\.apple\.com\z/) ||
+ host.match?(/\A[a-z0-9-]+(?:\.[a-z0-9-]+)*\.notify\.windows\.com\z/)
+ rescue URI::InvalidURIError
+ false
+ end
+
+ # Accepts both padded and unpadded Base64, rejecting non-base64 input.
+ def self.urlsafe_decode(value)
+ return unless value.is_a?(String) && value.match?(/\A[A-Za-z0-9_-]+={0,2}\z/)
+ Base64.urlsafe_decode64(value)
+ rescue ArgumentError
+ nil
+ end
+
+ def self.decode_key(value, length)
+ return unless value.is_a?(String)
+ decoded = urlsafe_decode(value)
+ return unless decoded && decoded.bytesize == length
+ return unless Base64.urlsafe_encode64(decoded, padding: false) == value.delete_suffix("==").delete_suffix("=")
+ decoded
+ end
+
+ def matches_keys?(public_key, secret)
+ decoded_public = self.class.urlsafe_decode(p256dh)
+ decoded_auth = self.class.urlsafe_decode(auth)
+ submitted_public = self.class.urlsafe_decode(public_key)
+ submitted_auth = self.class.urlsafe_decode(secret)
+ return false unless decoded_public && decoded_auth && submitted_public && submitted_auth
+
+ ActiveSupport::SecurityUtils.secure_compare(decoded_public, submitted_public) &&
+ ActiveSupport::SecurityUtils.secure_compare(decoded_auth, submitted_auth)
+ end
+
+ def eligible?
+ user.active? && session.user_id == user_id && !session.expired?
+ end
+
+ # Rate limits mirror the controller-level per-user limiter; this per-device
+ # cooldown keeps one browser tab with an auto-retrying script from spamming
+ # the delivery path.
+ def request_test_notification!
+ with_lock do
+ if last_test_requested_at && last_test_requested_at > TEST_NOTIFICATION_COOLDOWN.ago
+ next nil
+ end
+ update!(last_test_requested_at: Time.current)
+ push_deliveries.create!
+ end
+ end
+
+ def self.channel_ready?
+ WebPush::Client.configured?
+ end
+
+ # The browser adapter for PushDelivery. Lock-screen text stays generic.
+ def deliver(delivery)
+ payload = I18n.with_locale(user.family.locale) do
+ {
+ title: Rails.configuration.x.product_name,
+ body: I18n.t(delivery.insight ? "web_push.notification.body" : "web_push.notification.test_body"),
+ tag: delivery.insight ? "insight-#{delivery.insight_id}" : "web-push-test-#{delivery.id}",
+ data: { path: delivery.insight ? "/insights#insight_#{delivery.insight_id}" : "/insights" }
+ }
+ end
+ WebPush::Client.new.deliver(subscription: self, payload: payload)
+ rescue WebPush::Client::TransientError => e
+ raise PushDelivery::TransientError, e.message
+ end
+
+ private
+ def set_endpoint_digest
+ if self.class.allowed_endpoint?(endpoint)
+ uri = URI.parse(endpoint)
+ uri.host = uri.host.downcase
+ self.endpoint = uri.to_s
+ end
+ self.endpoint_digest = Digest::SHA256.hexdigest(endpoint.to_s)
+ end
+
+ def validate_destination
+ errors.add(:endpoint, :invalid) unless self.class.allowed_endpoint?(endpoint)
+ end
+
+ def validate_session_owner
+ errors.add(:session, :invalid) unless session && user && session.user_id == user.id && !session.expired? && user.active?
+ end
+
+ def validate_keys
+ public_key = self.class.decode_key(p256dh, 65)
+ secret = self.class.decode_key(auth, 16)
+ errors.add(:auth, :invalid) unless secret
+ unless public_key && public_key.getbyte(0) == 4
+ errors.add(:p256dh, :invalid)
+ return
+ end
+ group = OpenSSL::PKey::EC::Group.new("prime256v1")
+ point = OpenSSL::PKey::EC::Point.new(group, OpenSSL::BN.new(public_key, 2))
+ errors.add(:p256dh, :invalid) unless point.on_curve? && !point.infinity?
+ rescue OpenSSL::OpenSSLError, ArgumentError
+ errors.add(:p256dh, :invalid)
+ end
+end
diff --git a/app/views/pwa/service-worker.js b/app/views/pwa/service-worker.js
index 4108a20651..8f409637b3 100644
--- a/app/views/pwa/service-worker.js
+++ b/app/views/pwa/service-worker.js
@@ -57,29 +57,61 @@ self.addEventListener('fetch', (event) => {
}
});
-// Add a service worker for processing Web Push notifications:
-//
-// self.addEventListener("push", async (event) => {
-// const { title, options } = await event.data.json()
-// event.waitUntil(self.registration.showNotification(title, options))
-// })
-//
-// self.addEventListener("notificationclick", function(event) {
-// event.notification.close()
-// event.waitUntil(
-// clients.matchAll({ type: "window" }).then((clientList) => {
-// for (let i = 0; i < clientList.length; i++) {
-// let client = clientList[i]
-// let clientPath = (new URL(client.url)).pathname
-//
-// if (clientPath == event.notification.data.path && "focus" in client) {
-// return client.focus()
-// }
-// }
-//
-// if (clients.openWindow) {
-// return clients.openWindow(event.notification.data.path)
-// }
-// })
-// )
-// })
+// Only notification links into the insight feed are accepted. Provider payloads
+// never grant an arbitrary URL permission to open or navigate a browser window.
+function insightNotificationPath(value) {
+ try {
+ const url = new URL(value, self.location.origin);
+ if (url.origin === self.location.origin && url.pathname === "/insights") {
+ const anchor = /^#insight_[0-9a-f-]{36}$/i.test(url.hash) ? url.hash : "";
+ return `/insights${anchor}`;
+ }
+ } catch {
+ // A malformed or absent destination returns to the feed.
+ }
+ return "/insights";
+}
+
+self.addEventListener("push", (event) => {
+ let payload = {};
+ try {
+ const data = event.data?.json();
+ if (data && typeof data === "object") payload = data;
+ } catch {
+ // Even an empty or malformed push must display a visible notification.
+ }
+
+ event.waitUntil(
+ self.registration.showNotification(typeof payload.title === "string" && payload.title ? payload.title : "Sure", {
+ body: typeof payload.body === "string" ? payload.body : "",
+ icon: "/android-chrome-192x192.png",
+ tag: typeof payload.tag === "string" ? payload.tag : "sure-financial-alert",
+ data: { path: insightNotificationPath(payload.data?.path) },
+ }),
+ );
+});
+
+self.addEventListener("notificationclick", (event) => {
+ event.notification.close();
+ const path = insightNotificationPath(event.notification.data?.path);
+ const destination = new URL(path, self.location.origin);
+
+ event.waitUntil(
+ self.clients.matchAll({ type: "window", includeUncontrolled: true }).then(async (windows) => {
+ for (const client of windows) {
+ const url = new URL(client.url);
+ if (url.origin === destination.origin && url.pathname === destination.pathname && "focus" in client) {
+ if ("navigate" in client) {
+ try {
+ await client.navigate(destination.href);
+ } catch {
+ continue;
+ }
+ }
+ return client.focus();
+ }
+ }
+ return self.clients.openWindow(destination.href);
+ }),
+ );
+});
diff --git a/app/views/settings/preferences/_web_push.html.erb b/app/views/settings/preferences/_web_push.html.erb
new file mode 100644
index 0000000000..91c086501f
--- /dev/null
+++ b/app/views/settings/preferences/_web_push.html.erb
@@ -0,0 +1,35 @@
+<%= settings_section title: t("web_push.title"), subtitle: t("web_push.description") do %>
+ <div class="space-y-4"
+ data-controller="web-push"
+ data-web-push-public-key-value="<%= @web_push_public_key %>"
+ data-web-push-registrations-value="<%= @web_push_registrations.to_json %>"
+ data-web-push-url-value="<%= web_push_subscriptions_path %>"
+ data-web-push-messages-value="<%= t("web_push.status").merge(t("web_push.errors")).to_json %>">
+ <%= render DS::Pill.new(label: t("web_push.preview")) %>
+ <p class="text-sm text-secondary" role="status" aria-live="polite" data-web-push-target="status"><%= t("web_push.status.checking") %></p>
+ <div class="hidden" data-web-push-target="iosGuidance">
+ <%= render DS::Alert.new(message: t("web_push.ios_guidance"), variant: :info) %>
+ </div>
+ <div class="flex flex-wrap gap-2">
+ <%= render DS::Button.new(text: t("web_push.enable"), disabled: true,
+ data: { action: "web-push#enable", web_push_target: "enable" }) %>
+ <%= render DS::Button.new(text: t("web_push.disable"), variant: :secondary, disabled: true,
+ data: { action: "web-push#disable", web_push_target: "disable" }) %>
+ <%= render DS::Button.new(text: t("web_push.test"), variant: :secondary, disabled: true,
+ data: { action: "web-push#test", web_push_target: "test" }) %>
+ </div>
+ <p class="text-sm text-secondary"><%= t("web_push.session_notice") %></p>
+ <%= form_with url: settings_preferences_path, method: :patch,
+ data: { controller: "auto-submit-form" } do %>
+ <label for="user_push_budget_warnings_enabled" class="flex cursor-pointer items-center justify-between gap-4">
+ <div class="text-sm space-y-1">
+ <p class="font-medium text-primary"><%= t("web_push.budget_title") %></p>
+ <p class="text-secondary"><%= t("web_push.budget_description") %></p>
+ </div>
+ <%= render DS::Toggle.new(id: "user_push_budget_warnings_enabled",
+ name: "user[push_budget_warnings_enabled]", checked: @user.push_budget_warnings_enabled?,
+ data: { auto_submit_form_target: "auto" }) %>
+ </label>
+ <% end %>
+ </div>
+<% end %>
diff --git a/app/views/settings/preferences/show.html.erb b/app/views/settings/preferences/show.html.erb
index 61a350beb3..2ea014fcb6 100644
--- a/app/views/settings/preferences/show.html.erb
+++ b/app/views/settings/preferences/show.html.erb
@@ -342,3 +342,7 @@
</label>
<% end %>
<% end %>
+
+<% if preview_features_enabled? %>
+ <%= render "web_push" %>
+<% end %>
diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb
index 478bfc39ca..6ee54847a3 100644
--- a/config/initializers/filter_parameter_logging.rb
+++ b/config/initializers/filter_parameter_logging.rb
@@ -4,6 +4,7 @@
# Use this to limit dissemination of sensitive information.
# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors.
Rails.application.config.filter_parameters += [
+ :endpoint, :p256dh, /\Aauth\z/i,
:passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :openai_access_token,
:client_id, :application_id, :consumer_key, :snaptrade_user_id, :snaptrade_user_secret,
:oauth_access_token, :oauth_refresh_token, :code_verifier, :code_challenge,
diff --git a/config/locales/views/web_push/de.yml b/config/locales/views/web_push/de.yml
new file mode 100644
index 0000000000..f27c2404bf
--- /dev/null
+++ b/config/locales/views/web_push/de.yml
@@ -0,0 +1,5 @@
+de:
+ web_push:
+ notification:
+ body: Eine neue Finanzmeldung ist verfügbar. Öffne Sure, um sie anzusehen.
+ test_body: Deine Testbenachrichtigung ist angekommen. Öffne Sure, um fortzufahren.
diff --git a/config/locales/views/web_push/en.yml b/config/locales/views/web_push/en.yml
new file mode 100644
index 0000000000..9c2545e6b3
--- /dev/null
+++ b/config/locales/views/web_push/en.yml
@@ -0,0 +1,38 @@
+en:
+ web_push:
+ title: Browser notifications
+ description: Receive new high-priority insights on this browser or installed app. Notifications hide financial details on your lock screen.
+ enable: Enable this device
+ disable: Disable this device
+ test: Test this device
+ preview: Preview
+ session_notice: Notifications stop when you sign out or your session expires after 30 days of inactivity. Open Sure regularly to keep your session active.
+ ios_guidance: On iPhone or iPad, open Sure in Safari, choose Share → Add to Home Screen, then enable notifications from the installed app. Requires iOS or iPadOS 16.4 or later.
+ budget_title: Budget warnings
+ budget_description: Also notify me when a budget category nears its limit. Over-budget alerts are always sent. Off by default; applies to all my push devices, browser and iOS.
+ notification:
+ body: A new financial alert is available. Open Sure to review it.
+ test_body: Your test notification has arrived. Open Sure to continue.
+ status:
+ checking: Checking this device…
+ enabled: Notifications are enabled for this device and session.
+ disabled: Notifications are disabled for this device.
+ denied: Notifications are blocked in browser settings. Allow them there, then enable this device again.
+ unsupported: This browser does not support notifications. Use a compatible browser or installed app over HTTPS.
+ unconfigured: Browser notifications have not been configured on this server.
+ queued: Test queued. Waiting for the push service to accept it.
+ accepted: Accepted by the push service. Check this device for the notification; acceptance does not confirm it was displayed.
+ skipped: Test skipped because this session or preview access changed, or the test expired. Enable this device and try again.
+ rejected: The push service rejected this test. Disable this device, then enable it again.
+ failed: The test could not be delivered. Try again later.
+ enqueue_failed: The test could not be queued. Try again later.
+ pending: Test queued or retrying. Delivery may take a moment.
+ expired: The test is still queued. Check background workers or try another test later.
+ errors:
+ registration: Could not register this device. Try disabling it, then enabling it again.
+ preview: Enable preview features before using browser notifications.
+ unconfigured: Browser notifications have not been configured on this server.
+ rate_limited: Too many notification requests. Wait a minute, then try again.
+ enqueue: Could not queue the test notification. Try again later.
+ request: Could not update browser notifications. Check your connection and try again.
+ permission: Notification permission was not granted.
diff --git a/config/routes.rb b/config/routes.rb
index 931b32d652..0185f34293 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -2,6 +2,10 @@ require "sidekiq/web"
require "sidekiq/cron/web"
Rails.application.routes.draw do
+ resources :web_push_subscriptions, only: [ :create, :show, :destroy ] do
+ post :test_notification, on: :member
+ end
+
resources :questrade_items, only: [ :index, :new, :create, :show, :edit, :update, :destroy ] do
collection do
get :preload_accounts
diff --git a/config/schedule.yml b/config/schedule.yml
index fde324357e..157cf91df7 100644
--- a/config/schedule.yml
+++ b/config/schedule.yml
@@ -32,6 +32,13 @@ sync_hourly:
queue: "scheduled"
description: "Syncs provider items that opt-in to hourly syncing"
+recover_push_deliveries:
+ cron: "*/15 * * * *" # PushDelivery::CLAIM_TIMEOUT
+ class: "RecoverPushDeliveriesJob"
+ active_job: true
+ queue: "scheduled"
+ description: "Re-enqueues push deliveries whose enqueue failed or whose claim was abandoned"
+
sync_scheduled_items:
cron: "*/15 * * * *" # SyncSchedule::TICK
class: "SyncScheduledItemsJob"
diff --git a/db/migrate/20261029090000_create_push_notifications.rb b/db/migrate/20261029090000_create_push_notifications.rb
new file mode 100644
index 0000000000..df407ccbe6
--- /dev/null
+++ b/db/migrate/20261029090000_create_push_notifications.rb
@@ -0,0 +1,42 @@
+class CreatePushNotifications < ActiveRecord::Migration[8.1]
+ def change
+ add_column :insights, :notification_version, :integer, default: 1, null: false
+
+ create_table :web_push_subscriptions, id: :uuid do |t|
+ t.references :user, null: false, type: :uuid, foreign_key: true
+ # Session cleanup can delete rows without callbacks; the browser
+ # subscription goes with its session.
+ t.references :session, null: false, type: :uuid, foreign_key: { on_delete: :cascade }
+ t.text :endpoint, null: false
+ t.string :endpoint_digest, null: false
+ t.text :p256dh, null: false
+ t.text :auth, null: false
+ t.datetime :last_test_requested_at
+ t.timestamps
+ end
+ add_index :web_push_subscriptions, :endpoint_digest, unique: true
+
+ # One delivery ledger for every push channel. The subscription is
+ # polymorphic, so it has no foreign key.
+ create_table :push_deliveries, id: :uuid do |t|
+ t.references :subscription, polymorphic: true, null: false, type: :uuid
+ t.references :insight, type: :uuid, foreign_key: true
+ t.integer :insight_version
+ t.string :status, null: false, default: "pending"
+ t.datetime :enqueued_at
+ t.datetime :attempted_at
+ t.integer :provider_attempts, null: false, default: 0
+ t.timestamps
+ end
+ add_index :push_deliveries, [ :subscription_type, :subscription_id, :insight_id, :insight_version ],
+ unique: true, name: "index_push_deliveries_on_channel_insight_version"
+ add_index :push_deliveries, [ :status, :updated_at ]
+ add_check_constraint :push_deliveries,
+ "status IN ('pending', 'accepted', 'skipped', 'rejected', 'failed', 'enqueue_failed')",
+ name: "chk_push_deliveries_status"
+ add_check_constraint :push_deliveries,
+ "(insight_id IS NULL AND insight_version IS NULL) OR (insight_id IS NOT NULL AND insight_version IS NOT NULL AND insight_version > 0)",
+ name: "chk_push_deliveries_insight_version"
+ add_check_constraint :push_deliveries, "provider_attempts >= 0", name: "chk_push_deliveries_provider_attempts"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 06f21c4baa..e3d7883521 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1489,6 +1489,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_19_120000) do
t.datetime "generated_at", default: -> { "CURRENT_TIMESTAMP" }, null: false
t.string "insight_type", null: false
t.jsonb "metadata", default: {}, null: false
+ t.integer "notification_version", default: 1, null: false
t.date "period_end"
t.date "period_start"
t.string "priority", default: "medium", null: false
@@ -1992,6 +1993,26 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_19_120000) do
t.index ["provider_key", "period"], name: "index_provider_request_counts_on_provider_key_and_period", unique: true
end
+ create_table "push_deliveries", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.datetime "attempted_at"
+ t.datetime "created_at", null: false
+ t.datetime "enqueued_at"
+ t.uuid "insight_id"
+ t.integer "insight_version"
+ t.integer "provider_attempts", default: 0, null: false
+ t.string "status", default: "pending", null: false
+ t.uuid "subscription_id", null: false
+ t.string "subscription_type", null: false
+ t.datetime "updated_at", null: false
+ t.index ["insight_id"], name: "index_push_deliveries_on_insight_id"
+ t.index ["status", "updated_at"], name: "index_push_deliveries_on_status_and_updated_at"
+ t.index ["subscription_type", "subscription_id", "insight_id", "insight_version"], name: "index_push_deliveries_on_channel_insight_version", unique: true
+ t.index ["subscription_type", "subscription_id"], name: "index_push_deliveries_on_subscription"
+ t.check_constraint "insight_id IS NULL AND insight_version IS NULL OR insight_id IS NOT NULL AND insight_version IS NOT NULL AND insight_version > 0", name: "chk_push_deliveries_insight_version"
+ t.check_constraint "provider_attempts >= 0", name: "chk_push_deliveries_provider_attempts"
+ t.check_constraint "status::text = ANY (ARRAY['pending'::character varying, 'accepted'::character varying, 'skipped'::character varying, 'rejected'::character varying, 'failed'::character varying, 'enqueue_failed'::character varying]::text[])", name: "chk_push_deliveries_status"
+ end
+
create_table "push_subscriptions", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.datetime "created_at", null: false
t.string "device_key_digest"
@@ -3044,6 +3065,21 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_19_120000) do
t.integer "year"
end
+ create_table "web_push_subscriptions", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.text "auth", null: false
+ t.datetime "created_at", null: false
+ t.text "endpoint", null: false
+ t.string "endpoint_digest", null: false
+ t.datetime "last_test_requested_at"
+ t.text "p256dh", null: false
+ t.uuid "session_id", null: false
+ t.datetime "updated_at", null: false
+ t.uuid "user_id", null: false
+ t.index ["endpoint_digest"], name: "index_web_push_subscriptions_on_endpoint_digest", unique: true
+ t.index ["session_id"], name: "index_web_push_subscriptions_on_session_id"
+ t.index ["user_id"], name: "index_web_push_subscriptions_on_user_id"
+ end
+
create_table "webauthn_credentials", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.datetime "created_at", null: false
t.string "credential_id", null: false
@@ -3235,6 +3271,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_19_120000) do
add_foreign_key "plaid_accounts", "plaid_items"
add_foreign_key "plaid_items", "families"
add_foreign_key "plaid_items", "users", column: "owner_id", on_delete: :nullify
+ add_foreign_key "push_deliveries", "insights"
add_foreign_key "push_subscriptions", "users"
add_foreign_key "questrade_accounts", "questrade_items"
add_foreign_key "questrade_items", "families"
@@ -3305,6 +3342,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_19_120000) do
add_foreign_key "users", "accounts", column: "default_account_id", on_delete: :nullify
add_foreign_key "users", "chats", column: "last_viewed_chat_id"
add_foreign_key "users", "families"
+ add_foreign_key "web_push_subscriptions", "sessions", on_delete: :cascade
+ add_foreign_key "web_push_subscriptions", "users"
add_foreign_key "webauthn_credentials", "users"
add_foreign_key "weekly_cleanup_runs", "families", on_delete: :cascade
add_foreign_key "weekly_cleanup_runs", "users", on_delete: :cascade
diff --git a/docs/hosting/push-notifications.md b/docs/hosting/push-notifications.md
index c8b4802cd6..6e19893c7b 100644
--- a/docs/hosting/push-notifications.md
+++ b/docs/hosting/push-notifications.md
@@ -22,7 +22,7 @@ and Sidekiq workers:
Base64 does not encrypt the signing key. Do not embed it in the iOS app, logs, or
repository. Configure the same shared Rails Redis cache on web and worker
processes; a process-local memory/null cache cannot coordinate these diagnostics.
-Workers must consume the existing `scheduled` queue and reach the sandbox and
+Workers must consume the existing `scheduled` and `high_priority` queues and reach the sandbox and
production APNs endpoints over HTTP/2/TLS. No additional gem or database migration
is needed for the System Health diagnostic.
@@ -88,3 +88,109 @@ registration error state, and navigation for insight/test notification taps.
Durable insight delivery tracking and recovery across enqueue failures are a
separate implementation step. Provisioning and live sandbox/TestFlight acceptance
must be completed before declaring push delivery ready for rollout.
+
+# Browser and installed PWA notifications
+
+Browser Web Push is a separate preview feature available in both managed and
+self-hosted installations. It does not require an Apple Developer account or
+change the hosted-only native APNs restrictions above. It reuses existing
+insights; it does not introduce additional financial analysis or thresholds.
+
+## Configure Web Push
+
+Run the included database migrations and set these variables in the secret store
+for both Rails and Sidekiq:
+
+| Variable | Purpose |
+| --- | --- |
+| `WEB_PUSH_VAPID_PUBLIC_KEY` | URL-safe Base64 public VAPID key; shared with browsers |
+| `WEB_PUSH_VAPID_PRIVATE_KEY` | Matching URL-safe Base64 private VAPID key; server-side only |
+| `WEB_PUSH_VAPID_SUBJECT` | Operator contact URI, such as `mailto:[email protected]` or an HTTPS URL |
+
+Generate the key pair once with the maintained `web-push` gem, for example from
+your deployment's Rails console using `WebPush.generate_key`. Store its
+`public_key` and `private_key` in your secret store. Keep the same pair on web and
+worker processes and across deploys. Never commit the private key. Rotating the
+pair requires a new browser subscription; Enable this device replaces an old-key
+subscription when the browser is next enabled.
+
+The application must be served over HTTPS, and workers must consume `high_priority` and `scheduled`.
+Allow outbound TLS on port 443 to the browser push services: `fcm.googleapis.com`,
+`updates.push.services.mozilla.com`, subdomains of `push.apple.com`, and subdomains
+of `notify.windows.com`. Registration accepts only those HTTPS destinations,
+without user info, fragments, or nonstandard ports. Provider redirects are rejected.
+The `web-push` gem handles encryption and VAPID signing; Sure does not implement
+its own notification cryptography. Endpoints and subscription keys are filtered
+from request logs and encrypted at rest when Rails encryption is configured.
+
+## Enable and verify a device
+
+1. Sign in, turn on **Settings → Preferences → Enable preview features**, then
+ select **Enable this device** in **Browser notifications**. Permission is
+ requested only from that button. Each browser profile or installed app must
+ opt in separately.
+2. On iPhone and iPad, use Safari's **Share → Add to Home Screen**, open the
+ installed app, sign in there, and enable notifications there. Web Push requires
+ iOS/iPadOS 16.4 or later. Other browser and operating system support varies.
+3. Select **Test this device**. Only the registration bound to this browser's
+ current Sure session can be tested. The control is limited to once per
+ 30 seconds per registration and twice per minute across the signed-in user's
+ devices.
+4. Wait for the displayed result, then check the actual device. **Queued** means
+ the background job was queued. **Accepted by the push service** means the
+ provider accepted it; it does not prove that the operating system displayed
+ it. Browser permission, Focus/Do Not Disturb, and OS settings affect display.
+
+Each user can have up to 20 browser subscriptions. Renewing an existing device
+or moving it to a new session does not consume another slot. Remove unused
+devices or revoke their sessions in Security settings before adding more.
+Registration requests are limited to 10 per minute per user. Production uses
+the existing shared Rails cache (Redis) to coordinate request limits.
+
+Notifications are bound to the authenticated Sure session. Signing out, revoking
+that session, deactivating the account, or **30 days of session inactivity** stops
+delivery. Open Sure regularly to refresh the existing session; after expiry,
+sign in and enable this device again. The normal session timeout is unchanged.
+Disabling preview features also stops sends. Use **Disable this device** before
+changing accounts on shared devices. When a browser is registered under another
+session or user, the existing subscription's two secret keys prove continuity;
+Sure replaces the old row so queued jobs cannot reach the new account through it.
+
+## Alerts, privacy, and delivery behavior
+
+Every channel uses one policy, `Insight#notifies?`: an enabled device receives
+new or materially resurfaced, high-priority active insights visible to the
+family, including over-budget `budget_at_risk` warnings. Enabling a device does
+not send a backlog. **Budget warnings** is a per-user preference, off by
+default, that adds the medium-priority near-limit `budget_at_risk` insights on
+all of that user's push devices, browser and iOS. `budget_on_track` is low
+priority and never pushed. Existing financial generators and category
+thresholds are unchanged.
+
+Lock-screen payloads contain the product name and generic localized text, with
+no balances, categories, accounts, or insight prose. They use the family's
+locale and link to the same-origin `/insights#insight_<id>` page. The service worker
+displays a visible notification, including for malformed payloads, and caches only
+the existing offline assets; it does not cache financial pages.
+
+A durable delivery ledger records each eligible subscription together with its
+material insight version in the same database transaction. Recipients are fixed
+at that event: later device registration or budget opt-in does not add a backlog.
+Routine generator refreshes do not create a new version. Send-time checks repeat
+session, user, preview, budget preference, family, active insight, version, and
+shared-account visibility checks. Retries and ordinary duplicate jobs reuse the
+same ledger entry. HTTP 404/410 removes an invalid subscription. Connection
+failures, HTTP 429, and HTTP 5xx receive at most five provider attempts across
+recovered jobs, with bounded backoff. Each attempt is reserved durably before
+contacting the provider, so an interrupted worker still consumes its attempt;
+other rejections are terminal. Each send has connection and read timeouts and a
+five-minute provider TTL.
+
+`RecoverPushDeliveriesJob` runs every 15 minutes (`config/schedule.yml`) and
+re-enqueues enqueue failures and pending claims abandoned for more than 15
+minutes that are still eligible. Records that are no longer eligible become
+skipped. It does not replay terminal results or turn old insights into a
+backlog. A provider acceptance followed by a process
+crash before the database update can still result in a duplicate send. Stable
+notification tags collapse ordinary duplicate presentations where the browser
+supports them; this is not an exactly-once transport guarantee.
diff --git a/lib/active_record_encryption_config.rb b/lib/active_record_encryption_config.rb
index a5751db0cb..da0b5b5989 100644
--- a/lib/active_record_encryption_config.rb
+++ b/lib/active_record_encryption_config.rb
@@ -70,7 +70,7 @@ module ActiveRecordEncryptionConfig
# older, narrower version back into "not complete" until they re-run the
# task - otherwise the legacy-plaintext fallback would get disabled for
# models the install's last backfill never actually covered.
- CURRENT_BACKFILL_VERSION = 11
+ CURRENT_BACKFILL_VERSION = 12
# Single source of truth for which models/fields security:backfill_encryption
# covers, keyed by the same symbol the task's `results` hash uses. Model
@@ -126,6 +126,7 @@ module ActiveRecordEncryptionConfig
trading212_items: [ "Trading212Item", %i[api_key api_secret raw_instruments_payload] ],
up_items: [ "UpItem", %i[access_token raw_payload raw_institution_payload] ],
wise_items: [ "WiseItem", %i[token raw_payload sca_private_key] ],
+ web_push_subscriptions: [ "WebPushSubscription", %i[endpoint p256dh auth] ],
plaid_accounts: [ "PlaidAccount", %i[raw_payload raw_transactions_payload raw_holdings_payload raw_liabilities_payload] ],
simplefin_accounts: [ "SimplefinAccount", %i[raw_payload raw_transactions_payload raw_holdings_payload] ],
lunchflow_accounts: [ "LunchflowAccount", %i[raw_payload raw_transactions_payload raw_holdings_payload] ],
diff --git a/test/controllers/settings/preferences_controller_test.rb b/test/controllers/settings/preferences_controller_test.rb
index 12ee880741..c6ad38c686 100644
--- a/test/controllers/settings/preferences_controller_test.rb
+++ b/test/controllers/settings/preferences_controller_test.rb
@@ -126,6 +126,62 @@ class Settings::PreferencesControllerTest < ActionDispatch::IntegrationTest
assert_not_includes response.body, I18n.t("settings.preferences.show.budget_sharing_title")
end
+ test "browser notification card is preview gated" do
+ get settings_preferences_url
+ assert_select "[data-controller='web-push']", count: 0
+ user = users(:family_admin)
+ user.update!(preferences: user.preferences.merge("preview_features_enabled" => true))
+ get settings_preferences_url
+ assert_select "[data-controller='web-push']", count: 1
+ assert_select "input[name='user[push_budget_warnings_enabled]']"
+ end
+
+ test "budget warnings default off and are saved only for this user" do
+ user = users(:family_admin)
+ other = users(:family_member)
+ user.update!(preferences: user.preferences.merge("preview_features_enabled" => true))
+ assert_not user.push_budget_warnings_enabled?
+ patch settings_preferences_url, params: { user: { push_budget_warnings_enabled: "1" } }
+ assert_redirected_to settings_preferences_url
+ assert user.reload.push_budget_warnings_enabled?
+ assert_not other.reload.push_budget_warnings_enabled?
+ patch settings_preferences_url, params: { user: { push_budget_warnings_enabled: "0" } }
+ assert_not user.reload.push_budget_warnings_enabled?
+ end
+
+ test "browser registration inventory contains only current session ids and digests" do
+ require Rails.root.join("test/support/web_push_test_helper")
+ extend WebPushTestHelper
+ user = users(:family_admin)
+ user.update!(preferences: user.preferences.merge("preview_features_enabled" => true))
+ current_session = Current.session
+ device = register_web_push(user: user, session: current_session)
+ other = register_web_push(user: user, endpoint: "https://fcm.googleapis.com/other")
+ get settings_preferences_url
+ inventory = JSON.parse(css_select("[data-web-push-registrations-value]").first["data-web-push-registrations-value"])
+ assert_equal({ device.id => device.endpoint_digest }, inventory)
+ assert_not_includes inventory.keys, other.id
+ assert_not_includes response.body, device.endpoint
+ assert_not_includes response.body, device.auth
+ end
+
+ test "enabling preview and budget warnings together saves both values" do
+ user = users(:family_admin)
+ user.update!(preferences: {})
+ patch settings_preferences_url, params: { user: { preview_features_enabled: "1", push_budget_warnings_enabled: "1" } }
+ assert_redirected_to settings_preferences_url
+ assert user.reload.preview_features_enabled?
+ assert user.push_budget_warnings_enabled?
+ end
+
+ test "disabling preview in the request prevents enabling budget warnings" do
+ user = users(:family_admin)
+ user.update!(preferences: { "preview_features_enabled" => true })
+ patch settings_preferences_url, params: { user: { preview_features_enabled: "0", push_budget_warnings_enabled: "1" } }
+ assert_not user.reload.preview_features_enabled?
+ assert_not user.push_budget_warnings_enabled?
+ end
+
test "admins with preview access see the manual reconciliation toggle" do
user = users(:family_admin)
user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => true))
diff --git a/test/controllers/web_push_subscriptions_controller_test.rb b/test/controllers/web_push_subscriptions_controller_test.rb
new file mode 100644
index 0000000000..5ea10f2ad5
--- /dev/null
+++ b/test/controllers/web_push_subscriptions_controller_test.rb
@@ -0,0 +1,133 @@
+require "test_helper"
+require Rails.root.join("test/support/web_push_test_helper")
+
+class WebPushSubscriptionsControllerTest < ActionDispatch::IntegrationTest
+ include WebPushTestHelper
+ include ActiveJob::TestHelper
+
+ setup do
+ @user = users(:family_admin)
+ enable_web_push_preview(@user)
+ sign_in @user
+ @session = Current.session
+ @attributes = web_push_attributes
+ WebPush::Client.stubs(:configured?).returns(true)
+ end
+
+ test "registration requires an authenticated cookie session" do
+ delete session_url(@session)
+ post "/web_push_subscriptions", params: @attributes, as: :json
+ assert_redirected_to new_session_url
+ end
+
+ test "registration requires preview opt in" do
+ @user.update!(preferences: {})
+ assert_no_difference "WebPushSubscription.count" do
+ post "/web_push_subscriptions", params: @attributes, as: :json
+ assert_response :forbidden
+ end
+ end
+
+ test "registers for the current session in self hosted mode without a backlog" do
+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ assert_no_enqueued_jobs do
+ assert_difference "WebPushSubscription.count", 1 do
+ post "/web_push_subscriptions", params: @attributes, as: :json
+ end
+ end
+ assert_response :created
+ subscription = WebPushSubscription.find(response.parsed_body.fetch("id"))
+ assert_equal @user.id, subscription.user_id
+ assert_equal @session.id, subscription.session_id
+ assert_not_includes response.body, @attributes[:endpoint]
+ assert_not_includes response.body, @attributes[:auth]
+ end
+
+ test "registration is unavailable without VAPID configuration" do
+ WebPush::Client.stubs(:configured?).returns(false)
+ post "/web_push_subscriptions", params: @attributes, as: :json
+ assert_response :service_unavailable
+ end
+
+ test "rejects invalid subscriptions without persisting them" do
+ assert_no_difference "WebPushSubscription.count" do
+ post "/web_push_subscriptions", params: @attributes.merge(endpoint: "https://localhost/private"), as: :json
+ assert_response :unprocessable_entity
+ end
+ end
+
+ test "cannot delete or test a different session's device" do
+ other = register_web_push(user: @user)
+ delete "/web_push_subscriptions/#{other.id}", as: :json
+ assert_response :not_found
+ post "/web_push_subscriptions/#{other.id}/test_notification", as: :json
+ assert_response :not_found
+ assert WebPushSubscription.exists?(other.id)
+ end
+
+ test "removes only the current device" do
+ device = register_web_push(user: @user, session: @session)
+ delete "/web_push_subscriptions/#{device.id}", as: :json
+ assert_response :no_content
+ assert_not WebPushSubscription.exists?(device.id)
+ end
+
+ test "testing the current device reports queued rather than provider accepted and is throttled" do
+ device = register_web_push(user: @user, session: @session)
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ post "/web_push_subscriptions/#{device.id}/test_notification", as: :json
+ assert_response :accepted
+ assert_equal "queued", response.parsed_body.fetch("status")
+ post "/web_push_subscriptions/#{device.id}/test_notification", as: :json
+ assert_response :too_many_requests
+ end
+ end
+
+ test "impersonation sessions cannot register or manage the impersonated user's browser push devices" do
+ impersonation_session = impersonation_sessions(:in_progress)
+ impersonated = impersonation_session.impersonated
+ enable_web_push_preview(impersonated)
+ device = register_web_push(user: impersonated)
+
+ sign_in impersonation_session.impersonator
+ post join_impersonation_sessions_path, params: { impersonation_session_id: impersonation_session.id }
+ assert_redirected_to root_path
+
+ assert_no_difference "WebPushSubscription.count" do
+ post "/web_push_subscriptions", params: @attributes, as: :json
+ assert_response :forbidden
+ end
+
+ delete "/web_push_subscriptions/#{device.id}", as: :json
+ assert_response :forbidden
+ post "/web_push_subscriptions/#{device.id}/test_notification", as: :json
+ assert_response :forbidden
+ assert WebPushSubscription.exists?(device.id)
+ end
+
+ test "web registration retains Rails CSRF protection" do
+ previous = ActionController::Base.allow_forgery_protection
+ ActionController::Base.allow_forgery_protection = true
+ post "/web_push_subscriptions", params: @attributes, as: :json
+ assert_response :unprocessable_entity
+ ensure
+ ActionController::Base.allow_forgery_protection = previous
+ end
+ test "test requests are rate limited across all devices of the user" do
+ WebPushSubscriptionsController.cache_store.stubs(:increment)
+ .with { |key, *| key.include?("web-push-test") && key.end_with?(@user.id) }
+ .returns(1, 2, 3)
+ devices = 3.times.map { |i| register_web_push(user: @user, session: @session, endpoint: "https://fcm.googleapis.com/rate-#{i}") }
+ assert_enqueued_jobs 2, only: DeliverInsightNotificationJob do
+ devices.first(2).each do |device|
+ post "/web_push_subscriptions/#{device.id}/test_notification", as: :json
+ assert_response :accepted
+ end
+ assert_no_difference "PushDelivery.count" do
+ post "/web_push_subscriptions/#{devices.last.id}/test_notification", as: :json
+ assert_response :too_many_requests
+ assert_equal I18n.t("web_push.errors.rate_limited"), response.parsed_body.fetch("error")
+ end
+ end
+ end
+end
diff --git a/test/integration/push_delivery_concurrency_test.rb b/test/integration/push_delivery_concurrency_test.rb
new file mode 100644
index 0000000000..7b3f860bf2
--- /dev/null
+++ b/test/integration/push_delivery_concurrency_test.rb
@@ -0,0 +1,95 @@
+require "test_helper"
+require "timeout"
+require Rails.root.join("test/support/web_push_test_helper")
+
+class PushDeliveryConcurrencyTest < ActiveSupport::TestCase
+ include WebPushTestHelper
+ self.use_transactional_tests = false
+
+ test "re-registration completes during provider IO and a late gone response preserves the replacement" do
+ user = users(:family_admin)
+ original_preferences = user.preferences.deep_dup
+ enable_web_push_preview(user)
+ old_session = user.sessions.create!
+ new_session = user.sessions.create!
+ attributes = web_push_attributes
+ subscription = register_web_push(user: user, session: old_session, **attributes)
+ delivery = subscription.push_deliveries.create!(enqueued_at: Time.current)
+ started = Queue.new
+ release = Queue.new
+ errors = Queue.new
+ replacement = nil
+ client = Object.new
+ client.define_singleton_method(:deliver) do |**_arguments|
+ started << true
+ release.pop
+ :gone
+ end
+ WebPush::Client.stubs(:configured?).returns(true)
+ WebPush::Client.stubs(:new).returns(client)
+
+ worker = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+ rescue => error
+ errors << error
+ end
+ Timeout.timeout(10) { started.pop }
+ registrar = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ replacement = WebPushSubscription.register_for!(user: User.find(user.id), session: Session.find(new_session.id), **attributes)
+ end
+ rescue => error
+ errors << error
+ end
+
+ assert registrar.join(3), "Registration must not wait for a provider response or take an inverse delivery lock"
+ release << true
+ assert worker.join(10), "The late provider response must finish without deadlocking"
+ assert errors.empty?, errors.empty? ? nil : errors.pop.full_message
+ assert WebPushSubscription.exists?(replacement.id)
+ assert_not WebPushSubscription.exists?(subscription.id)
+ ensure
+ release << true if release
+ [ registrar, worker ].compact.each do |thread|
+ thread.join(10)
+ thread.kill if thread.alive?
+ end
+ WebPushSubscription.where(session_id: [ old_session&.id, new_session&.id ].compact).destroy_all
+ [ old_session, new_session ].compact.each(&:destroy!)
+ user&.update!(preferences: original_preferences) if original_preferences
+ end
+ test "simultaneous registrations cannot exceed the per-user device limit" do
+ user = users(:family_admin)
+ session = user.sessions.create!
+ 19.times { |i| register_web_push(user: user, session: session, endpoint: "https://fcm.googleapis.com/cap-existing-#{i}") }
+ start = Queue.new
+ results = Queue.new
+ workers = 2.times.map do |i|
+ Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ start.pop
+ register_web_push(user: User.find(user.id), session: Session.find(session.id), endpoint: "https://fcm.googleapis.com/cap-concurrent-#{i}")
+ results << :registered
+ rescue ActiveRecord::RecordInvalid
+ results << :limited
+ rescue => error
+ results << error
+ end
+ end
+ end
+ 2.times { start << true }
+ workers.each { |worker| assert worker.join(10), "Registration must finish without a lock cycle" }
+ outcomes = 2.times.map { results.pop }
+ assert_equal 1, outcomes.count(:registered), outcomes.inspect
+ assert_equal 1, outcomes.count(:limited), outcomes.inspect
+ assert_equal 20, user.web_push_subscriptions.count
+ ensure
+ workers&.each do |worker|
+ worker.join(10)
+ worker.kill if worker.alive?
+ end
+ session&.destroy!
+ end
+end
diff --git a/test/javascript/web_push_controller_test.mjs b/test/javascript/web_push_controller_test.mjs
new file mode 100644
index 0000000000..b462e07d4c
--- /dev/null
+++ b/test/javascript/web_push_controller_test.mjs
@@ -0,0 +1,296 @@
+import assert from "node:assert/strict";
+import { webcrypto } from "node:crypto";
+import { readFile } from "node:fs/promises";
+import { test } from "node:test";
+import vm from "node:vm";
+
+const source = (await readFile(new URL("../../app/javascript/controllers/web_push_controller.js", import.meta.url), "utf8"))
+ .replace(/^import .*;\n/m, "")
+ .replace("export default class extends Controller", "globalThis.WebPushController = class extends Controller");
+
+async function controller({ endpoint, registrations, subscriptionKey = [1, 2, 3], unsubscribeSucceeds = true }) {
+ const calls = { permission: 0, subscribe: 0, fetch: 0, unsubscribe: 0 };
+ const posts = [];
+ const timers = new Map();
+ let nextTimer = 0;
+ const makeSubscription = (url, key) => ({
+ endpoint: url,
+ options: { applicationServerKey: Uint8Array.from(key).buffer },
+ toJSON: () => ({ endpoint: url, keys: { p256dh: "public-key", auth: "secret" } }),
+ unsubscribe: async () => {
+ calls.unsubscribe++;
+ if (unsubscribeSucceeds) current = null;
+ return unsubscribeSucceeds;
+ },
+ });
+ let current = makeSubscription(endpoint, subscriptionKey);
+ const registration = { pushManager: {
+ getSubscription: async () => current,
+ subscribe: async (options) => {
+ calls.subscribe++;
+ current = makeSubscription(`${endpoint}-rotated`, options.applicationServerKey);
+ return current;
+ },
+ } };
+ const context = vm.createContext({
+ Controller: class {},
+ window: { isSecureContext: true, PushManager: class {}, Notification: {}, matchMedia: () => ({ matches: false }) },
+ navigator: { userAgent: "Desktop", platform: "Linux", maxTouchPoints: 0, serviceWorker: {
+ getRegistration: async () => registration,
+ ready: Promise.resolve(registration),
+ } },
+ Notification: { permission: "granted", requestPermission: () => { calls.permission++; } },
+ crypto: webcrypto,
+ TextEncoder,
+ Uint8Array,
+ atob,
+ clearTimeout: (id) => timers.delete(id),
+ setTimeout: (callback) => { const id = ++nextTimer; timers.set(id, callback); return id; },
+ document: { querySelector: () => ({ content: "csrf-token" }) },
+ fetch: async (_url, options) => {
+ calls.fetch++;
+ if (options.method === "POST" && options.body) posts.push(JSON.parse(options.body));
+ return { status: options.method === "DELETE" ? 204 : 201, ok: true, json: async () => ({ id: "new-id" }) };
+ },
+ });
+ vm.runInContext(source, context);
+ const instance = new context.WebPushController();
+ instance.publicKeyValue = "AQID";
+ instance.registrationsValue = registrations;
+ instance.subscriptionIdValue = Object.keys(registrations)[0] || "";
+ instance.urlValue = "/web_push_subscriptions";
+ instance.messagesValue = { accepted: "accepted", pending: "pending", enabled: "enabled", disabled: "disabled", request: "Localized retry guidance" };
+ instance.iosGuidanceTarget = { classList: { toggle() {} } };
+ instance.statusTarget = {};
+ instance.enableTarget = {};
+ instance.disableTarget = {};
+ instance.testTarget = {};
+ await instance.connect();
+ return { instance, calls, posts, timers, context };
+}
+
+async function digest(endpoint) {
+ return Buffer.from(await webcrypto.subtle.digest("SHA-256", new TextEncoder().encode(endpoint))).toString("hex");
+}
+
+test("a rotated endpoint cannot test or disable an unrelated server registration", async () => {
+ const { instance, calls } = await controller({ endpoint: "https://fcm.googleapis.com/new", registrations: {
+ "old-id": await digest("https://fcm.googleapis.com/old"),
+ } });
+ assert.equal(instance.subscriptionIdValue, "");
+ assert.equal(instance.enableTarget.disabled, false);
+ assert.equal(instance.disableTarget.disabled, true);
+ assert.equal(instance.testTarget.disabled, true);
+ assert.equal(instance.statusTarget.textContent, "disabled");
+ assert.deepEqual(calls, { permission: 0, subscribe: 0, fetch: 0, unsubscribe: 0 });
+});
+
+test("the local endpoint matches its own record rather than the newest session record", async () => {
+ const endpoint = "https://fcm.googleapis.com/local";
+ const { instance } = await controller({ endpoint, registrations: {
+ "newest-other-id": await digest("https://fcm.googleapis.com/other"),
+ "local-id": await digest(endpoint),
+ } });
+ assert.equal(instance.subscriptionIdValue, "local-id");
+ assert.equal(instance.enableTarget.disabled, true);
+ assert.equal(instance.testTarget.disabled, false);
+ assert.equal(instance.disableTarget.disabled, false);
+ assert.equal(instance.statusTarget.textContent, "enabled");
+});
+
+test("native browser failures display localized guidance without raw exception details", async () => {
+ const { instance } = await controller({ endpoint: "https://fcm.googleapis.com/local", registrations: {} });
+ await instance.run(async () => { throw new Error("Native browser error with internal details"); });
+ assert.equal(instance.statusTarget.textContent, "Localized retry guidance");
+});
+
+test("enable replaces an old VAPID subscription when its server registration is gone", async () => {
+ const { instance, calls, posts } = await controller({ endpoint: "https://fcm.googleapis.com/old", registrations: {}, subscriptionKey: [9, 8, 7] });
+ await instance.enable();
+ assert.equal(calls.unsubscribe, 1);
+ assert.equal(calls.subscribe, 1);
+ assert.equal(posts[0].endpoint, "https://fcm.googleapis.com/old-rotated");
+ assert.equal(instance.statusTarget.textContent, "enabled");
+});
+
+test("a registered endpoint with an old VAPID key is not advertised as enabled", async () => {
+ const endpoint = "https://fcm.googleapis.com/old";
+ const { instance, calls } = await controller({ endpoint, registrations: { "old-id": await digest(endpoint) }, subscriptionKey: [9, 8, 7] });
+ assert.equal(instance.statusTarget.textContent, "disabled");
+ assert.equal(instance.enableTarget.disabled, false);
+ assert.equal(instance.testTarget.disabled, true);
+ assert.equal(calls.unsubscribe, 0);
+ await instance.enable();
+ assert.equal(calls.unsubscribe, 1);
+ assert.equal(calls.subscribe, 1);
+ assert.equal(calls.fetch, 2);
+});
+
+test("enable reuses a browser subscription already bound to the current VAPID key", async () => {
+ const { instance, calls, posts } = await controller({ endpoint: "https://fcm.googleapis.com/current", registrations: {} });
+ await instance.enable();
+ assert.equal(calls.unsubscribe, 0);
+ assert.equal(calls.subscribe, 0);
+ assert.equal(posts[0].endpoint, "https://fcm.googleapis.com/current");
+});
+
+test("failed old-key unsubscription does not register or report a working replacement", async () => {
+ const { instance, calls } = await controller({ endpoint: "https://fcm.googleapis.com/old", registrations: {}, subscriptionKey: [9, 8, 7], unsubscribeSucceeds: false });
+ await instance.enable();
+ assert.equal(calls.fetch, 0);
+ assert.equal(calls.subscribe, 0);
+ assert.equal(instance.statusTarget.textContent, "Localized retry guidance");
+});
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+}
+
+test("disable invalidates a poll already awaiting a provider result", async () => {
+ const endpoint = "https://fcm.googleapis.com/local";
+ const { instance, timers } = await controller({ endpoint, registrations: { "local-id": await digest(endpoint) } });
+ const response = deferred();
+ instance.request = (_url, method) => method === "GET" ? response.promise : Promise.resolve({});
+ const polling = instance.pollTest();
+ await instance.disable();
+ response.resolve({ test_status: "accepted" });
+ await polling;
+ assert.equal(instance.statusTarget.textContent, "disabled");
+ assert.equal(timers.size, 0);
+});
+
+test("a new failed Test cancels the earlier timer and ignores its in-flight result", async () => {
+ const endpoint = "https://fcm.googleapis.com/local";
+ const { instance, timers } = await controller({ endpoint, registrations: { "local-id": await digest(endpoint) } });
+ instance.messagesValue.queued = "queued";
+ await instance.test();
+ assert.equal(timers.size, 1);
+ const response = deferred();
+ instance.request = (_url, method) => {
+ if (method === "GET") return response.promise;
+ return Promise.reject(Object.assign(new Error("429"), { userMessage: "Too many tests" }));
+ };
+ const polling = instance.pollTest();
+ await instance.test();
+ response.resolve({ test_status: "pending" });
+ await polling;
+ assert.equal(instance.statusTarget.textContent, "Too many tests");
+ assert.equal(timers.size, 0);
+});
+
+test("disconnect invalidates late poll errors", async () => {
+ const { instance, timers } = await controller({ endpoint: "https://fcm.googleapis.com/local", registrations: {} });
+ const response = deferred();
+ instance.request = () => response.promise;
+ const polling = instance.pollTest();
+ instance.disconnect();
+ response.reject(new Error("Network failed"));
+ await polling;
+ assert.equal(instance.statusTarget.textContent, "disabled");
+ assert.equal(timers.size, 0);
+});
+
+test("a superseded poll 404 cannot remove a replacement registration", async () => {
+ const endpoint = "https://fcm.googleapis.com/local";
+ const { instance, context } = await controller({ endpoint, registrations: { "local-id": await digest(endpoint) } });
+ const response = deferred();
+ const originalFetch = context.fetch;
+ context.fetch = (url, options) => options.method === "GET" ? response.promise : originalFetch(url, options);
+ const polling = instance.pollTest();
+ await instance.disable();
+ await instance.enable();
+ response.resolve({ status: 404, ok: false, json: async () => ({}) });
+ await polling;
+ assert.equal(instance.subscriptionIdValue, "new-id");
+ assert.equal(instance.statusTarget.textContent, "enabled");
+ assert.equal(instance.testTarget.disabled, false);
+});
+
+test("reconnecting the same controller does not revive a previous connection's poll", async () => {
+ const endpoint = "https://fcm.googleapis.com/local";
+ const { instance } = await controller({ endpoint, registrations: { "local-id": await digest(endpoint) } });
+ const response = deferred();
+ instance.request = () => response.promise;
+ const polling = instance.pollTest();
+ instance.disconnect();
+ await instance.connect();
+ response.resolve({ test_status: "accepted" });
+ await polling;
+ assert.equal(instance.statusTarget.textContent, "enabled");
+});
+
+for (const status of [202, 404]) {
+ test(`a Test POST completing with ${status} after reconnect cannot change the new lifecycle`, async () => {
+ const endpoint = "https://fcm.googleapis.com/local";
+ const { instance, context, timers } = await controller({ endpoint, registrations: { "local-id": await digest(endpoint) } });
+ instance.messagesValue.queued = "queued";
+ const response = deferred();
+ context.fetch = () => response.promise;
+ const testing = instance.test();
+ instance.disconnect();
+ await instance.connect();
+ instance.busy = true;
+ instance.updateControls();
+ response.resolve({ status, ok: status === 202, json: async () => ({}) });
+ await testing;
+ assert.equal(instance.statusTarget.textContent, "enabled");
+ assert.equal(instance.subscriptionIdValue, "local-id");
+ assert.equal(instance.busy, true);
+ assert.equal(instance.testTarget.disabled, true);
+ assert.equal(timers.size, 0);
+ });
+}
+
+for (const action of ["enable", "disable"]) {
+ test(`an old ${action} continuation cannot overwrite a reconnected controller`, async () => {
+ const endpoint = "https://fcm.googleapis.com/local";
+ const registrations = action === "disable" ? { "local-id": await digest(endpoint) } : {};
+ const { instance } = await controller({ endpoint, registrations });
+ const entered = deferred();
+ const response = deferred();
+ instance.request = () => { entered.resolve(); return response.promise; };
+ const operation = instance[action]();
+ await entered.promise;
+ instance.disconnect();
+ await instance.connect();
+ const expectedStatus = instance.statusTarget.textContent;
+ const expectedId = instance.subscriptionIdValue;
+ response.resolve({ id: "old-operation-id" });
+ await operation;
+ assert.equal(instance.statusTarget.textContent, expectedStatus);
+ assert.equal(instance.subscriptionIdValue, expectedId);
+ });
+}
+
+for (const fails of [false, true]) {
+ test(`an old connect ${fails ? "error" : "result"} cannot overwrite a new connection`, async () => {
+ const endpoint = "https://fcm.googleapis.com/local";
+ const { instance, context } = await controller({ endpoint, registrations: { "local-id": await digest(endpoint) } });
+ const registration = await context.navigator.serviceWorker.getRegistration("/");
+ const original = registration.pushManager.getSubscription;
+ const entered = deferred();
+ const response = deferred();
+ let calls = 0;
+ registration.pushManager.getSubscription = () => {
+ if (++calls === 1) { entered.resolve(); return response.promise; }
+ return original();
+ };
+ const connecting = instance.connect();
+ await entered.promise;
+ instance.disconnect();
+ await instance.connect();
+ instance.busy = true;
+ instance.updateControls();
+ if (fails) response.reject(new Error("Old connection failed"));
+ else response.resolve(null);
+ await connecting;
+ assert.equal(instance.statusTarget.textContent, "enabled");
+ assert.equal(instance.subscriptionIdValue, "local-id");
+ assert.ok(instance.subscription);
+ assert.equal(instance.busy, true);
+ assert.equal(instance.testTarget.disabled, true);
+ });
+}
diff --git a/test/javascript/web_push_service_worker_test.mjs b/test/javascript/web_push_service_worker_test.mjs
new file mode 100644
index 0000000000..1f0044e690
--- /dev/null
+++ b/test/javascript/web_push_service_worker_test.mjs
@@ -0,0 +1,108 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { test } from "node:test";
+import vm from "node:vm";
+
+const source = await readFile(
+ new URL("../../app/views/pwa/service-worker.js", import.meta.url),
+ "utf8",
+);
+
+function worker(windows = []) {
+ const handlers = new Map();
+ const shown = [];
+ const opened = [];
+ const self = {
+ location: { origin: "https://sure.example" },
+ addEventListener: (name, handler) => handlers.set(name, handler),
+ registration: {
+ showNotification: async (title, options) => shown.push({ title, options }),
+ },
+ clients: {
+ matchAll: async () => windows,
+ openWindow: async (url) => opened.push(url),
+ },
+ };
+ vm.runInNewContext(source, { self, URL });
+ return { handlers, shown, opened };
+}
+
+async function dispatch(worker, name, event) {
+ const handler = worker.handlers.get(name);
+ assert.equal(typeof handler, "function", `${name} handler must be registered`);
+ let completion;
+ handler({ ...event, waitUntil: (promise) => { completion = promise; } });
+ assert.equal(typeof completion?.then, "function", `${name} must keep the worker alive`);
+ await completion;
+}
+
+test("a push visibly displays its generic server-localized message", async () => {
+ const state = worker();
+ const path = "/insights#insight_123e4567-e89b-12d3-a456-426614174000";
+ await dispatch(state, "push", {
+ data: { json: () => ({ title: "Sure", body: "A new financial alert is available.", data: { path } }) },
+ });
+ assert.equal(state.shown.length, 1);
+ assert.equal(state.shown[0].title, "Sure");
+ assert.equal(state.shown[0].options.body, "A new financial alert is available.");
+ assert.equal(state.shown[0].options.data.path, path);
+});
+
+test("notification titles respect the server product name", async () => {
+ const state = worker();
+ await dispatch(state, "push", {
+ data: { json: () => ({ title: "Sure Community", body: "A new financial alert is available." }) },
+ });
+ assert.equal(state.shown[0].title, "Sure Community");
+});
+
+test("an empty or malformed push still displays a visible notification", async () => {
+ for (const data of [undefined, { json: () => { throw new SyntaxError("bad payload"); } }]) {
+ const state = worker();
+ await dispatch(state, "push", { data });
+ assert.equal(state.shown.length, 1);
+ assert.equal(state.shown[0].title, "Sure");
+ }
+});
+
+test("notification clicks only open the same-origin insights page", async () => {
+ for (const path of ["https://evil.example/insights", "//evil.example/insights", "/accounts", "javascript:alert(1)", undefined]) {
+ const state = worker();
+ let closed = false;
+ await dispatch(state, "notificationclick", {
+ notification: { data: { path }, close: () => { closed = true; } },
+ });
+ assert.equal(closed, true);
+ assert.equal(state.opened.length, 1);
+ const destination = new URL(state.opened[0], "https://sure.example");
+ assert.equal(destination.origin, "https://sure.example");
+ assert.equal(destination.pathname, "/insights");
+ }
+});
+
+test("notification clicks retain the valid insight anchor", async () => {
+ const state = worker();
+ const path = "/insights#insight_123e4567-e89b-12d3-a456-426614174000";
+ await dispatch(state, "notificationclick", {
+ notification: { data: { path }, close: () => {} },
+ });
+ assert.equal(new URL(state.opened[0], "https://sure.example").hash,
+ "#insight_123e4567-e89b-12d3-a456-426614174000");
+});
+
+test("notification clicks navigate and focus the existing insights window", async () => {
+ const calls = [];
+ const path = "/insights#insight_123e4567-e89b-12d3-a456-426614174000";
+ const state = worker([{ url: "https://sure.example/insights", navigate: async (url) => calls.push(url), focus: async () => calls.push("focus") }]);
+ await dispatch(state, "notificationclick", { notification: { data: { path }, close() {} } });
+ assert.deepEqual(calls, [`https://sure.example${path}`, "focus"]);
+ assert.equal(state.opened.length, 0);
+});
+
+test("failed existing-window navigation falls back to a new insight window", async () => {
+ let focused = false;
+ const state = worker([{ url: "https://sure.example/insights", navigate: async () => { throw new Error("Window closed"); }, focus: async () => { focused = true; } }]);
+ await dispatch(state, "notificationclick", { notification: { data: { path: "/insights" }, close() {} } });
+ assert.equal(focused, false);
+ assert.deepEqual(state.opened, ["https://sure.example/insights"]);
+});
diff --git a/test/jobs/deliver_insight_notification_job_test.rb b/test/jobs/deliver_insight_notification_job_test.rb
index e6164561cd..fd9acb9a06 100644
--- a/test/jobs/deliver_insight_notification_job_test.rb
+++ b/test/jobs/deliver_insight_notification_job_test.rb
@@ -5,9 +5,9 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCase
Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
Apns::Client.stubs(:configured?).returns(true)
@insight = insights(:cash_flow_warning)
- user = @insight.family.users.first
- user.update!(preferences: user.preferences.merge("preview_features_enabled" => true))
- @subscription = user.push_subscriptions.create!(
+ @user = @insight.family.users.first
+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))
+ @subscription = @user.push_subscriptions.create!(
token: "ab" * 32,
environment: "sandbox",
platform: "ios",
@@ -15,19 +15,41 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCase
)
end
- test "a job queued before a device changed users cannot reach its replacement" do
- @subscription.update!(device_key_digest: Digest::SHA256.hexdigest("cd" * 32))
- old_id = @subscription.id
- next_user = @insight.family.users.where.not(id: @subscription.user_id).first!
- replacement = PushSubscription.register_for!(user: next_user, token: @subscription.token,
- environment: "sandbox", platform: "ios", device_key: "cd" * 32)
+ test "records one ledger row per subscription and replays never duplicate it" do
+ 2.times { PushDelivery.record_for_insight!(@insight) }
+ assert_equal 1, PushDelivery.apns.where(subscription: @subscription, insight: @insight).count
+ end
+
+ test "a material version records a fresh row without replaying the old one" do
+ first = record_delivery
+ @insight.increment!(:notification_version)
+ PushDelivery.record_for_insight!(@insight.reload)
+ assert_equal 2, PushDelivery.apns.where(insight: @insight).count
+
Apns::Client.expects(:new).never
- DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: old_id)
- assert PushSubscription.exists?(replacement.id)
- assert_not PushSubscription.exists?(old_id)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: first.id)
+ assert_equal "skipped", first.reload.status
+ end
+
+ test "records rows for opted-in users with recent devices only" do
+ opted_out = @insight.family.users.where.not(id: @user.id).first
+ opted_out.update!(preferences: opted_out.preferences.merge("preview_features_enabled" => false))
+ opted_out.push_subscriptions.create!(
+ token: "cd" * 32, environment: "sandbox", platform: "ios", last_registered_at: Time.current
+ )
+ stale = PushSubscription.create!(
+ user: @user, token: "ef" * 32, environment: "sandbox", platform: "ios",
+ last_registered_at: 91.days.ago
+ )
+
+ PushDelivery.record_for_insight!(@insight)
+
+ assert_equal [ @subscription.id ],
+ PushDelivery.apns.where(insight: @insight).pluck(:subscription_id)
end
- test "delivers a privacy-preserving insight notification" do
+ test "delivers a privacy-preserving insight notification from the ledger" do
+ delivery = record_delivery
response = stub(ok?: true)
client = mock
Apns::Client.expects(:new).with(environment: "sandbox").returns(client)
@@ -38,17 +60,14 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCase
insight_id: @insight.id
).returns(response)
- DeliverInsightNotificationJob.perform_now(
- insight_id: @insight.id,
- push_subscription_id: @subscription.id
- )
- end
-
- test "does not push an insight whose account is no longer shared with everyone" do
- @insight.update!(metadata: @insight.metadata.merge("account_id" => accounts(:connected).id))
- Apns::Client.expects(:new).never
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ end
+ clear_enqueued_jobs
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
- DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
+ assert_equal "accepted", delivery.reload.status
+ assert_equal 1, delivery.provider_attempts
end
test "does not push a household total computed from accounts someone can no longer open" do
@@ -60,6 +79,7 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCase
test "localizes notifications using the family locale" do
@insight.family.update!(locale: "de")
+ delivery = record_delivery
response = stub(ok?: true)
client = mock
Apns::Client.stubs(:new).returns(client)
@@ -70,71 +90,205 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCase
insight_id: @insight.id
).returns(response)
- DeliverInsightNotificationJob.perform_now(
- insight_id: @insight.id,
- push_subscription_id: @subscription.id
- )
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
end
- test "removes tokens rejected as unregistered" do
- response = stub(ok?: false, status: "410", body: { "reason" => "Unregistered" })
+ test "does not record or push an insight whose account is no longer shared with everyone" do
+ @insight.update!(metadata: @insight.metadata.merge("account_id" => accounts(:connected).id))
+ PushDelivery.record_for_insight!(@insight)
+ assert_empty PushDelivery.apns.where(insight: @insight)
+
+ Apns::Client.expects(:new).never
+ assert_no_enqueued_jobs do
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ end
+ end
+
+ test "low priority and non-active insights are never recorded or enqueued" do
+ Apns::Client.expects(:new).never
+ [ { priority: "low" }, { status: "read" }, { status: "expired" }, { status: "acknowledged" } ].each do |attributes|
+ @insight.update!(attributes)
+ PushDelivery.record_for_insight!(@insight)
+ assert_no_enqueued_jobs do
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ end
+ assert_empty PushDelivery.apns.where(insight: @insight)
+ end
+ end
+
+ test "eligibility changes after recording skip the send at claim time" do
+ delivery = record_delivery
+ @insight.mark_read!
+ Apns::Client.expects(:new).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_equal "skipped", delivery.reload.status
+ end
+
+ test "a stale registration cannot claim a recorded delivery" do
+ delivery = record_delivery
+ @subscription.update!(last_registered_at: 91.days.ago)
+ Apns::Client.expects(:new).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_equal "skipped", delivery.reload.status
+ end
+
+ test "a deactivated user cannot claim a recorded delivery" do
+ delivery = record_delivery
+ @subscription.user.update_column(:active, false)
+ Apns::Client.expects(:new).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_equal "skipped", delivery.reload.status
+ end
+
+ test "preview opt out after recording prevents delivery at claim time" do
+ delivery = record_delivery
+ @user.update!(preferences: {})
+ Apns::Client.expects(:new).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_equal "skipped", delivery.reload.status
+ end
+
+ test "a ledger row for a subscription that changed users cannot reach the replacement" do
+ delivery = record_delivery
+ @subscription.update!(device_key_digest: Digest::SHA256.hexdigest("cd" * 32))
+ next_user = @insight.family.users.where.not(id: @subscription.user_id).first!
+ replacement = PushSubscription.register_for!(user: next_user, token: @subscription.token,
+ environment: "sandbox", platform: "ios", device_key: "cd" * 32)
+ Apns::Client.expects(:new).never
+
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+
+ assert PushSubscription.exists?(replacement.id)
+ assert_not PushSubscription.exists?(@subscription.id)
+ assert_not PushDelivery.exists?(delivery.id)
+ end
+
+ test "transient failures hand the attempt back to the ledger and stay pending" do
+ delivery = record_delivery
+ response = stub(ok?: false, status: "503", body: {})
Apns::Client.any_instance.stubs(:deliver).returns(response)
- assert_difference "PushSubscription.count", -1 do
- DeliverInsightNotificationJob.perform_now(
- insight_id: @insight.id,
- push_subscription_id: @subscription.id
- )
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
end
+ assert_equal "pending", delivery.reload.status
+ assert_equal 1, delivery.reload.provider_attempts
end
- test "does not send an insight to a device from another family" do
- other_subscription = users(:empty).push_subscriptions.create!(
- token: "cd" * 32,
- environment: "sandbox",
- platform: "ios",
- last_registered_at: Time.current
- )
+ test "five transient attempts exhaust the ledger budget terminally" do
+ delivery = record_delivery
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ clear_enqueued_jobs
+ response = stub(ok?: false, status: "500", body: {})
+ Apns::Client.any_instance.stubs(:deliver).returns(response)
+
+ assert_performed_jobs 5, only: DeliverInsightNotificationJob do
+ perform_enqueued_jobs only: DeliverInsightNotificationJob do
+ DeliverInsightNotificationJob.perform_later(push_delivery_id: delivery.id)
+ end
+ end
+ assert_equal "failed", delivery.reload.status
+
Apns::Client.expects(:new).never
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+ end
- DeliverInsightNotificationJob.perform_now(
- insight_id: @insight.id,
- push_subscription_id: other_subscription.id
- )
+ test "a late accepted response cannot be replayed into a second push" do
+ delivery = record_delivery
+ response = stub(ok?: true)
+ Apns::Client.any_instance.expects(:deliver).once.returns(response)
+
+ 2.times { DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id) }
+ assert_equal "accepted", delivery.reload.status
+ assert_equal 1, delivery.reload.provider_attempts
+ end
+
+ test "unregistered tokens are invalidated together with their ledger rows" do
+ delivery = record_delivery
+ sibling = PushDelivery.create!(subscription: @subscription, insight: @insight, insight_version: 2)
+ response = stub(ok?: false, status: "410", body: { "reason" => "Unregistered" })
+ Apns::Client.any_instance.stubs(:deliver).returns(response)
+
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+
+ assert_not PushSubscription.exists?(@subscription.id)
+ assert_not PushDelivery.exists?(delivery.id)
+ assert_not PushDelivery.exists?(sibling.id)
end
- test "self hosted mode prevents enqueueing and execution of old jobs" do
+ test "self hosted mode records no apns rows and cannot execute a stale row" do
Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ PushDelivery.record_for_insight!(@insight)
+ assert_empty PushDelivery.apns.where(insight: @insight)
Apns::Client.expects(:new).never
assert_no_enqueued_jobs do
- DeliverInsightNotificationJob.enqueue_for(@insight)
- DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ stale_row = PushDelivery.create!(subscription: @subscription, insight: @insight,
+ insight_version: @insight.notification_version)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: stale_row.id)
+ assert_equal "pending", stale_row.reload.status
end
end
- test "preview opt out after enqueueing prevents delivery" do
- @subscription.user.update!(preferences: { "preview_features_enabled" => false })
+ test "a channel that cannot attempt releases the reservation without burning the budget" do
+ delivery = record_delivery
+ Apns::Client.stubs(:available?).returns(true, false)
Apns::Client.expects(:new).never
- DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
+
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+
+ assert_equal "pending", delivery.reload.status
+ assert_equal 0, delivery.reload.provider_attempts
+ assert_nil delivery.reload.attempted_at
+ assert_nil delivery.reload.enqueued_at
end
- test "stale registrations and inactive users cannot receive insight pushes" do
- @subscription.update!(last_registered_at: 91.days.ago)
- Apns::Client.expects(:new).never
- DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
- @subscription.update!(last_registered_at: Time.current)
- @subscription.user.update_column(:active, false)
- DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
+ test "configuration failures record as failed rather than a provider rejection" do
+ delivery = record_delivery
+ Apns::Client.stubs(:new).raises(Apns::Client::ConfigurationError, "bad key")
+
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+
+ assert_equal "failed", delivery.reload.status
+ assert_equal 1, delivery.reload.provider_attempts
end
- test "low priority and already read insights cannot enqueue or deliver" do
- Apns::Client.expects(:new).never
- [ { priority: "low" }, { priority: "high", status: "read" }, { status: "expired" }, { status: "acknowledged" } ].each do |attributes|
- @insight.update!(attributes)
- assert_no_enqueued_jobs do
- DeliverInsightNotificationJob.enqueue_for(@insight)
- DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: @subscription.id)
- end
+ test "jobs queued before the ledger still deliver exactly once" do
+ response = stub(ok?: true)
+ client = mock
+ Apns::Client.expects(:new).with(environment: "sandbox").returns(client)
+ client.expects(:deliver).once.returns(response)
+
+ 2.times do
+ DeliverInsightNotificationJob.perform_now(
+ insight_id: @insight.id, push_subscription_id: @subscription.id
+ )
end
+
+ row = PushDelivery.apns.find_by!(subscription: @subscription, insight: @insight,
+ insight_version: @insight.notification_version)
+ assert_equal "accepted", row.reload.status
+ assert_equal 1, row.provider_attempts
+ end
+
+ test "the budget warning opt in applies to APNs devices too" do
+ @insight.update!(insight_type: "budget_at_risk", priority: "medium")
+ PushDelivery.record_for_insight!(@insight)
+ assert_empty PushDelivery.apns.where(insight: @insight)
+
+ @user.update!(preferences: @user.preferences.merge("push_budget_warnings_enabled" => true))
+ PushDelivery.record_for_insight!(@insight)
+ assert_equal [ @subscription.id ], PushDelivery.apns.where(insight: @insight).pluck(:subscription_id)
end
+
+ private
+ def record_delivery
+ PushDelivery.record_for_insight!(@insight)
+ PushDelivery.apns.find_by!(subscription: @subscription, insight: @insight,
+ insight_version: @insight.notification_version)
+ end
end
diff --git a/test/jobs/deliver_insight_notification_job_web_push_test.rb b/test/jobs/deliver_insight_notification_job_web_push_test.rb
new file mode 100644
index 0000000000..caacbd40fa
--- /dev/null
+++ b/test/jobs/deliver_insight_notification_job_web_push_test.rb
@@ -0,0 +1,381 @@
+require "test_helper"
+require Rails.root.join("test/support/web_push_test_helper")
+
+class DeliverInsightNotificationJobWebPushTest < ActiveJob::TestCase
+ include WebPushTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ enable_web_push_preview(@user)
+ @insight = insights(:cash_flow_warning)
+ @subscription = register_web_push(user: @user)
+ WebPush::Client.stubs(:configured?).returns(true)
+ @client = mock
+ WebPush::Client.stubs(:new).returns(@client)
+ end
+
+ test "enqueues only once for a subscription and material insight version" do
+ assert_no_enqueued_jobs { PushDelivery.record_for_insight!(@insight) }
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ 2.times { PushDelivery.enqueue_insight_deliveries(@insight) }
+ end
+ assert_equal 1, PushDelivery.where(subscription: @subscription, insight: @insight).count
+ end
+
+ test "an enqueue failure is recovered by the recovery sweep" do
+ DeliverInsightNotificationJob.stubs(:perform_later).returns(false)
+ delivery = enqueue_delivery
+ assert_equal "enqueue_failed", delivery.reload.status
+ delivery.update_columns(created_at: 2.days.ago)
+ DeliverInsightNotificationJob.unstub(:perform_later)
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ end
+ assert_equal "pending", delivery.reload.status
+ @client.expects(:deliver).returns(:accepted)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_equal "accepted", delivery.reload.status
+ end
+
+ test "delivers generic lock screen content and a same origin insight link" do
+ delivery = enqueue_delivery
+ @client.expects(:deliver).with do |subscription:, payload:|
+ subscription.id == @subscription.id &&
+ payload[:title] == "Sure" &&
+ payload[:body] == I18n.t("web_push.notification.body") &&
+ payload[:data][:path] == "/insights#insight_#{@insight.id}" &&
+ !payload.to_json.include?(@insight.title) && !payload.to_json.include?(@insight.body)
+ end.returns(:accepted)
+ 2.times { DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id) }
+ assert_equal "accepted", delivery.reload.status
+ end
+
+ test "localizes the generic payload with the family locale" do
+ @insight.family.update!(locale: "de")
+ delivery = enqueue_delivery
+ @client.expects(:deliver).with do |subscription:, payload:|
+ payload[:body] == I18n.t("web_push.notification.body", locale: :de)
+ end.returns(:accepted)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+
+ test "a material version can be delivered again without replaying the old version" do
+ first = enqueue_delivery
+ @insight.increment!(:notification_version)
+ PushDelivery.record_for_insight!(@insight.reload)
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ PushDelivery.enqueue_insight_deliveries(@insight.reload)
+ end
+ assert_equal 2, PushDelivery.where(insight: @insight).count
+ @client.expects(:deliver).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: first.id)
+ end
+
+ test "near-limit budget warnings require the opt in" do
+ @insight.update!(insight_type: "budget_at_risk", priority: "medium")
+ assert_no_enqueued_jobs do
+ PushDelivery.record_for_insight!(@insight)
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ end
+ @user.update!(preferences: @user.preferences.merge("push_budget_warnings_enabled" => true))
+ PushDelivery.record_for_insight!(@insight)
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ end
+ end
+
+ test "over-budget warnings notify like any high priority insight" do
+ @insight.update!(insight_type: "budget_at_risk", priority: "high")
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ PushDelivery.record_for_insight!(@insight)
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ end
+ end
+
+ test "never sends budget on track or ordinary medium priority insights" do
+ @user.update!(preferences: @user.preferences.merge("push_budget_warnings_enabled" => true))
+ [ { insight_type: "budget_on_track", priority: "medium" },
+ { insight_type: "spending_anomaly", priority: "medium" },
+ { insight_type: "budget_at_risk", priority: "low" } ].each do |attributes|
+ @insight.update!(attributes)
+ assert_no_enqueued_jobs do
+ PushDelivery.record_for_insight!(@insight)
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ end
+ end
+ end
+
+ test "budget opt out after enqueue prevents delivery" do
+ @insight.update!(insight_type: "budget_at_risk", priority: "medium")
+ @user.update!(preferences: @user.preferences.merge("push_budget_warnings_enabled" => true))
+ delivery = enqueue_delivery
+ @user.update!(preferences: @user.preferences.merge("push_budget_warnings_enabled" => false))
+ @client.expects(:deliver).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+
+ [ { status: "read" }, { status: "dismissed" }, { status: "expired" },
+ { metadata: { account_id: "private_account" } }, { family_id: "other_family" } ].each do |attributes|
+ test "send rechecks insight eligibility after #{attributes.keys.first} changes to #{attributes.values.first}" do
+ delivery = enqueue_delivery
+ changed = attributes.deep_dup
+ changed[:metadata] = { account_id: accounts(:connected).id } if changed[:metadata]
+ changed[:family_id] = families(:empty).id if changed[:family_id]
+ @insight.update!(changed)
+ @client.expects(:deliver).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+ end
+
+ test "preview opt out after enqueue prevents delivery" do
+ delivery = enqueue_delivery
+ @user.update!(preferences: {})
+ @client.expects(:deliver).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+
+ test "deactivating the user after enqueue prevents delivery" do
+ delivery = enqueue_delivery
+ @user.update_column(:active, false)
+ @client.expects(:deliver).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+
+ test "expired revoked or replaced sessions cannot receive a queued notification" do
+ delivery = enqueue_delivery
+ @client.expects(:deliver).never
+ @subscription.session.update_columns(updated_at: 31.days.ago)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ @subscription.session.touch
+ attributes = @subscription.attributes.symbolize_keys.slice(:endpoint, :p256dh, :auth)
+ register_web_push(user: users(:family_member), **attributes)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+
+ test "self hosted mode delivers browser push independently of APNs restrictions" do
+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)
+ delivery = enqueue_delivery
+ @client.expects(:deliver).returns(:accepted)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_equal "accepted", delivery.reload.status
+ end
+
+ test "gone subscriptions are removed after provider rejection" do
+ delivery = enqueue_delivery
+ @client.expects(:deliver).returns(:gone)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_not WebPushSubscription.exists?(@subscription.id)
+ end
+
+ test "transient failures schedule a bounded retry without marking accepted" do
+ delivery = enqueue_delivery
+ @client.expects(:deliver).raises(WebPush::Client::TransientError)
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+ assert_not_equal "accepted", delivery.reload.status
+ end
+
+ test "five transient provider attempts fail terminally and cannot replay" do
+ delivery = enqueue_delivery
+ clear_enqueued_jobs
+ @client.expects(:deliver).raises(WebPush::Client::TransientError).times(5)
+
+ assert_performed_jobs 5, only: DeliverInsightNotificationJob do
+ perform_enqueued_jobs only: DeliverInsightNotificationJob do
+ DeliverInsightNotificationJob.perform_later(push_delivery_id: delivery.id)
+ end
+ end
+
+ assert_equal "failed", delivery.reload.status
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ RecoverPushDeliveriesJob.perform_now
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ end
+ assert_equal "failed", delivery.reload.status
+ end
+
+ test "recovered jobs share the provider attempt budget with the interrupted retry chain" do
+ delivery = enqueue_delivery
+ @client.expects(:deliver).raises(WebPush::Client::TransientError).times(5)
+ original_job = DeliverInsightNotificationJob.new(push_delivery_id: delivery.id)
+ 4.times { original_job.perform_now }
+ clear_enqueued_jobs
+
+ travel 16.minutes do
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ end
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+
+ assert_equal "failed", delivery.reload.status
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ RecoverPushDeliveriesJob.perform_now
+ end
+ end
+
+ test "an interrupted provider call consumes its durable attempt before recovery" do
+ delivery = enqueue_delivery
+ sequence = sequence("provider calls")
+ @client.expects(:deliver).raises(RuntimeError, "Worker interrupted").once.in_sequence(sequence)
+ @client.expects(:deliver).raises(WebPush::Client::TransientError).times(4).in_sequence(sequence)
+
+ assert_raises(RuntimeError) do
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+
+ travel 16.minutes do
+ RecoverPushDeliveriesJob.perform_now
+ replacement_job = DeliverInsightNotificationJob.new(push_delivery_id: delivery.id)
+ 4.times { replacement_job.perform_now }
+ end
+
+ assert_equal "failed", delivery.reload.status
+ end
+
+ test "an in-flight attempt cannot be duplicated or reclaimed just because its queue claim is old" do
+ delivery = enqueue_delivery
+ delivery.update!(enqueued_at: 1.hour.ago)
+ @client.expects(:deliver).once.with do |**_arguments|
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+ true
+ end.returns(:accepted)
+
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+
+ assert_equal "accepted", delivery.reload.status
+ assert_equal 1, delivery.provider_attempts
+ end
+
+ test "a gone response does not delete credentials refreshed during provider IO" do
+ delivery = enqueue_delivery
+ @client.expects(:deliver).with do |**_arguments|
+ travel 1.second do
+ register_web_push(user: @user, session: @subscription.session, endpoint: @subscription.endpoint)
+ end
+ true
+ end.returns(:gone)
+
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+
+ assert WebPushSubscription.exists?(@subscription.id)
+ assert_equal "rejected", delivery.reload.status
+ end
+
+ test "an abandoned pending claim is recovered after fifteen minutes" do
+ delivery = enqueue_delivery
+ clear_enqueued_jobs
+ travel 16.minutes do
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ end
+ assert_equal "pending", delivery.reload.status
+ assert_operator delivery.enqueued_at, :>, 1.minute.ago
+ @client.expects(:deliver).returns(:accepted)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_equal "accepted", delivery.reload.status
+ end
+ end
+
+ test "recovery preserves a recent pending claim without queueing it twice" do
+ delivery = enqueue_delivery
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ end
+ assert_equal "pending", delivery.reload.status
+ end
+
+ test "an unclaimed pending delivery is recovered without waiting for the claim timeout" do
+ PushDelivery.record_for_insight!(@insight)
+ delivery = PushDelivery.find_by!(subscription: @subscription, insight: @insight,
+ insight_version: @insight.notification_version)
+ assert_nil delivery.enqueued_at
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ end
+ assert_equal "pending", delivery.reload.status
+ assert_not_nil delivery.enqueued_at
+ end
+
+ test "recovery marks newly ineligible pending work skipped" do
+ delivery = enqueue_delivery
+ clear_enqueued_jobs
+ @insight.mark_read!
+ @client.expects(:deliver).never
+ travel 16.minutes do
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+ end
+ assert_equal "skipped", delivery.reload.status
+ end
+
+ %w[accepted rejected failed skipped].each do |terminal_status|
+ test "recovery and job replays preserve a terminal #{terminal_status} result" do
+ delivery = enqueue_delivery
+ clear_enqueued_jobs
+ delivery.update!(status: terminal_status, enqueued_at: 1.day.ago)
+ @client.expects(:deliver).never
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+ assert_equal terminal_status, delivery.reload.status
+ end
+ end
+
+ test "configuration removed after enqueue prevents delivery" do
+ delivery = enqueue_delivery
+ WebPush::Client.stubs(:configured?).returns(false)
+ @client.expects(:deliver).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ end
+
+ test "configuration outages preserve pending attempts until recovery" do
+ delivery = enqueue_delivery
+ clear_enqueued_jobs
+ WebPush::Client.stubs(:configured?).returns(false)
+ @client.expects(:deliver).never
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_equal "pending", delivery.reload.status
+ assert_equal 0, delivery.provider_attempts
+ travel 16.minutes do
+ assert_no_enqueued_jobs { RecoverPushDeliveriesJob.perform_now }
+ assert_equal "pending", delivery.reload.status
+ WebPush::Client.stubs(:configured?).returns(true)
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ end
+ end
+ end
+
+ test "configuration outages preserve enqueue failures for later recovery" do
+ DeliverInsightNotificationJob.stubs(:perform_later).returns(false)
+ delivery = enqueue_delivery
+ assert_equal "enqueue_failed", delivery.reload.status
+ WebPush::Client.stubs(:configured?).returns(false)
+ RecoverPushDeliveriesJob.perform_now
+ assert_equal "enqueue_failed", delivery.reload.status
+ WebPush::Client.stubs(:configured?).returns(true)
+ DeliverInsightNotificationJob.unstub(:perform_later)
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ RecoverPushDeliveriesJob.perform_now
+ end
+ end
+
+ private
+ def enqueue_delivery
+ PushDelivery.record_for_insight!(@insight)
+ PushDelivery.enqueue_insight_deliveries(@insight)
+ PushDelivery.find_by!(subscription: @subscription, insight: @insight,
+ insight_version: @insight.notification_version)
+ end
+end
diff --git a/test/jobs/demo_family_refresh_job_test.rb b/test/jobs/demo_family_refresh_job_test.rb
index 1614990491..0f9cbb379d 100644
--- a/test/jobs/demo_family_refresh_job_test.rb
+++ b/test/jobs/demo_family_refresh_job_test.rb
@@ -1,6 +1,9 @@
require "test_helper"
+require Rails.root.join("test/support/web_push_test_helper")
class DemoFamilyRefreshJobTest < ActiveJob::TestCase
+ include WebPushTestHelper
+
setup do
@demo_email = "[email protected]"
Rails.application.stubs(:config_for).with(:demo).returns({ "email" => @demo_email })
@@ -112,6 +115,7 @@ class DemoFamilyRefreshJobTest < ActiveJob::TestCase
Setting.demo_family_refresh_enabled = true
@demo_family.start_subscription!(Subscription::DEMO_STRIPE_ID)
session = Session.create!(user: @demo_user)
+ browser_push = register_web_push(user: @demo_user, session: session)
app = Doorkeeper::Application.create!(name: "Demo Retirement Test", redirect_uri: "https://example.com/callback", confidential: false)
token = Doorkeeper::AccessToken.create!( # pipelock:ignore Credential in URL
application: app, resource_owner_id: @demo_user.id, scopes: "read", expires_in: 1.year)
@@ -131,6 +135,7 @@ class DemoFamilyRefreshJobTest < ActiveJob::TestCase
end
assert_not @demo_user.reload.active?
assert_not Session.exists?(session.id)
+ assert_not WebPushSubscription.exists?(browser_push.id)
assert key.reload.revoked?
assert token.reload.revoked_at
assert grant.reload.revoked_at
diff --git a/test/jobs/generate_insights_job_test.rb b/test/jobs/generate_insights_job_test.rb
index 96f188d9a2..92d6af539e 100644
--- a/test/jobs/generate_insights_job_test.rb
+++ b/test/jobs/generate_insights_job_test.rb
@@ -1,6 +1,9 @@
require "test_helper"
+require Rails.root.join("test/support/web_push_test_helper")
class GenerateInsightsJobTest < ActiveJob::TestCase
+ include WebPushTestHelper
+
setup do
@family = families(:dylan_family)
enable_preview_features(@family)
@@ -138,14 +141,148 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
assert_enqueued_with(
job: DeliverInsightNotificationJob,
args: ->(args) {
- args.one? &&
- args.first[:insight_id].present? &&
- args.first[:push_subscription_id] == subscription.id
+ args.one? && args.first[:push_delivery_id].present?
}
) do
GenerateInsightsJob.perform_now(family_id: @family.id)
end
end
+ assert_equal [ subscription.id ],
+ PushDelivery.apns.where(insight: @family.insights).pluck(:subscription_id)
+ end
+
+ test "browser push uses new and materially resurfaced insights but not routine refreshes" do
+ require Rails.root.join("test/support/web_push_test_helper")
+ extend WebPushTestHelper
+ user = @family.users.first
+ register_web_push(user: user)
+ WebPush::Client.stubs(:configured?).returns(true)
+ stub_generated([ generated_insight(priority: "high") ])
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ insight = @family.insights.find_by!(dedup_key: "idle_cash:test-account:2026-07")
+ original_version = insight.notification_version
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ assert_equal original_version, insight.reload.notification_version
+ insight.update!(status: "expired")
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ assert_equal original_version + 1, insight.reload.notification_version
+ end
+
+ test "a material metadata change increments the browser delivery version" do
+ register_web_push(user: @family.users.first)
+ WebPush::Client.stubs(:configured?).returns(true)
+ stub_generated([ generated_insight(priority: "high") ])
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ insight = @family.insights.find_by!(dedup_key: "idle_cash:test-account:2026-07")
+ version = insight.notification_version
+ stub_generated([ generated_insight(balance: 7500.0, priority: "high") ])
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ assert_equal version + 1, insight.reload.notification_version
+ assert_equal [ version, version + 1 ], PushDelivery.where(insight: insight).order(:insight_version).pluck(:insight_version)
+ end
+
+ test "deleting a device between eligibility and delivery recording preserves the insight" do
+ subscription = register_web_push(user: @family.users.first)
+ WebPush::Client.stubs(:configured?).returns(true)
+ stub_generated([ generated_insight(priority: "high") ])
+ WebPushSubscription.any_instance.stubs(:eligible?).with do
+ WebPushSubscription.where(id: subscription.id).delete_all
+ true
+ end.returns(true)
+ assert_difference "Insight.count", 1 do
+ assert_no_difference "PushDelivery.count" do
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ end
+ end
+
+ test "a failed broadcast does not hold back the push and an unchanged rerun sends nothing new" do
+ subscription = register_web_push(user: @family.users.first)
+ WebPush::Client.stubs(:configured?).returns(true)
+ stub_generated([ generated_insight(priority: "high") ])
+ Turbo::StreamsChannel.stubs(:broadcast_replace_to).raises(StandardError, "Broadcast unavailable")
+
+ assert_enqueued_jobs 1, only: DeliverInsightNotificationJob do
+ assert_raises(StandardError) { GenerateInsightsJob.perform_now(family_id: @family.id) }
+ end
+
+ Turbo::StreamsChannel.stubs(:broadcast_replace_to).returns(nil)
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ assert_equal 1, subscription.push_deliveries.count
+ end
+
+ test "a ledger failure rolls back a newly generated insight and its version" do
+ register_web_push(user: @family.users.first)
+ WebPush::Client.stubs(:configured?).returns(true)
+ stub_generated([ generated_insight(priority: "high") ])
+ PushDelivery.stubs(:for_subscription).raises(ActiveRecord::RecordInvalid.new(PushDelivery.new))
+
+ assert_no_difference [ "Insight.count", "PushDelivery.count" ] do
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ end
+ end
+
+ test "a ledger failure rolls back a material insight change with its delivery records" do
+ register_web_push(user: @family.users.first)
+ WebPush::Client.stubs(:configured?).returns(true)
+ stub_generated([ generated_insight(priority: "high") ])
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ insight = @family.insights.find_by!(dedup_key: "idle_cash:test-account:2026-07")
+ original_metadata = insight.metadata
+ original_version = insight.notification_version
+ stub_generated([ generated_insight(balance: 7500.0, priority: "high") ])
+ PushDelivery.stubs(:for_subscription).raises(ActiveRecord::RecordInvalid.new(PushDelivery.new))
+
+ assert_no_difference "PushDelivery.count" do
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ end
+ assert_equal original_version, insight.reload.notification_version
+ assert_equal original_metadata, insight.metadata
+ end
+
+ test "a device registered after an insight event receives no backlog" do
+ WebPush::Client.stubs(:configured?).returns(true)
+ stub_generated([ generated_insight(priority: "high") ])
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ insight = @family.insights.find_by!(dedup_key: "idle_cash:test-account:2026-07")
+ subscription = register_web_push(user: @family.users.first)
+
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ PushDelivery.enqueue_insight_deliveries(insight)
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ assert_empty subscription.push_deliveries
+ end
+
+ test "budget warning opt in after an insight event receives no backlog" do
+ user = @family.users.first
+ subscription = register_web_push(user: user)
+ WebPush::Client.stubs(:configured?).returns(true)
+ generated = generated_insight(priority: "medium").with(insight_type: "budget_at_risk")
+ stub_generated([ generated ])
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ insight = @family.insights.find_by!(dedup_key: generated.dedup_key)
+ user.update!(preferences: user.preferences.merge("push_budget_warnings_enabled" => true))
+
+ assert_no_enqueued_jobs only: DeliverInsightNotificationJob do
+ PushDelivery.enqueue_insight_deliveries(insight)
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+ assert_empty subscription.push_deliveries
end
test "re-running with unchanged numbers does not duplicate or rewrite" do
@@ -184,12 +321,24 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
end
test "a body refreshed in place is not notified again" do
+ user = @family.users.first
+ register_web_push(user: user)
+ WebPush::Client.stubs(:configured?).returns(true)
stub_generated([ generated_insight(priority: "high") ])
GenerateInsightsJob.perform_now(family_id: @family.id)
+ insight = @family.insights.find_by(dedup_key: "idle_cash:test-account:2026-07")
+ original_version = insight.notification_version
+ clear_enqueued_jobs
- DeliverInsightNotificationJob.expects(:enqueue_for).never
stub_generated([ generated_insight(priority: "high", display_balance: 5040) ])
- GenerateInsightsJob.perform_now(family_id: @family.id)
+ assert_no_enqueued_jobs do
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+ end
+
+ insight.reload
+ assert_equal original_version, insight.notification_version
+ assert_equal 1, PushDelivery.count
+ assert_equal "pending", PushDelivery.order(:created_at).last.reload.status
end
test "an expired insight that returns with new display facts gets a fresh body" do
diff --git a/test/lib/tasks/security_backfill_test.rb b/test/lib/tasks/security_backfill_test.rb
index 5134f44272..47bc808d41 100644
--- a/test/lib/tasks/security_backfill_test.rb
+++ b/test/lib/tasks/security_backfill_test.rb
@@ -384,7 +384,8 @@ class SecurityBackfillTest < ActiveSupport::TestCase
8 => "a4d113aa214e8754361484267d377174b2aeda3fe01c5ca0c553f9ab76ef2ab0",
9 => "9f814939a5125a6903d9ba4e96392056ffafe9f6110b10b5c1cae0d87a564ac7",
10 => "0bcaa72ed675acde5d5ae2ce72305bf73375c0faa5580fe80e3985e88aa4f9e4",
- 11 => "e706a4aba7b25ef1ec3d9dacbd6ca489e4abe577b54875ac377a48138890b450"
+ 11 => "e706a4aba7b25ef1ec3d9dacbd6ca489e4abe577b54875ac377a48138890b450",
+ 12 => "4122d5a8520c242fb5bad505511319806da13ed45996b47df2cb2ee34a4c041f"
}.freeze
test "backfill manifest changes come with a CURRENT_BACKFILL_VERSION bump" do
diff --git a/test/models/provider/enable_banking_test.rb b/test/models/provider/enable_banking_test.rb
index c7d4d46ef2..9fbb76b8ba 100644
--- a/test/models/provider/enable_banking_test.rb
+++ b/test/models/provider/enable_banking_test.rb
@@ -1,6 +1,7 @@
require "test_helper"
require "ostruct"
require "openssl"
+require "base64"
class Provider::EnableBankingTest < ActiveSupport::TestCase
setup do
@@ -456,6 +457,28 @@ class Provider::EnableBankingTest < ActiveSupport::TestCase
assert_not requested_queries.second.key?(:strategy)
end
+ # Checked with OpenSSL rather than the jwt gem that signs it, so a gem bump
+ # cannot pass by agreeing with itself.
+ test "signs requests with an RS256 JWT for the application" do
+ key = OpenSSL::PKey::RSA.new(2048)
+ provider = Provider::EnableBanking.new(application_id: "test_app_id", client_certificate: key.to_pem)
+ authorization = nil
+ Provider::EnableBanking.expects(:get).with do |_url, options|
+ authorization = options[:headers]["Authorization"]
+ true
+ end.returns(OpenStruct.new(code: 200, body: { aspsps: [] }.to_json))
+
+ freeze_time do
+ provider.get_aspsps(country: "FI")
+
+ header, payload, signature = authorization.delete_prefix("Bearer ").split(".")
+ assert key.public_key.verify("SHA256", Base64.urlsafe_decode64(signature), "#{header}.#{payload}")
+ assert_equal({ "typ" => "JWT", "alg" => "RS256", "kid" => "test_app_id" }, JSON.parse(Base64.urlsafe_decode64(header)))
+ claims = JSON.parse(Base64.urlsafe_decode64(payload))
+ assert_equal({ "iss" => "enablebanking.com", "aud" => "api.enablebanking.com", "iat" => Time.current.to_i, "exp" => Time.current.to_i + 3600 }, claims)
+ end
+ end
+
# The settings panel asks for the application's private key. Setups that
# pasted the key followed by a certificate must keep working.
test "accepts a private key followed by a certificate" do
diff --git a/test/models/provider/plaid_test.rb b/test/models/provider/plaid_test.rb
index 6003753493..39d015bd87 100644
--- a/test/models/provider/plaid_test.rb
+++ b/test/models/provider/plaid_test.rb
@@ -177,7 +177,107 @@ class Provider::PlaidTest < ActiveSupport::TestCase
end
end
+ test "verifies a webhook token against the JWK published for its kid" do
+ provider, jwk, key, body = verified_webhook_setup
+
+ token = JWT.encode(
+ { iat: Time.current.to_i, request_body_sha256: Digest::SHA256.hexdigest(body) },
+ key, "ES256", { "kid" => jwk.kid }
+ )
+
+ assert_nothing_raised { provider.validate_webhook!(token, body) }
+ end
+
+ test "rejects webhook tokens signed by a key with a matching kid but different bytes" do
+ provider, jwk, = verified_webhook_setup
+ impostor = OpenSSL::PKey::EC.generate("prime256v1")
+
+ token = JWT.encode(
+ { iat: Time.current.to_i, request_body_sha256: Digest::SHA256.hexdigest("{}") },
+ impostor, "ES256", { "kid" => jwk.kid }
+ )
+
+ assert_raises JWT::VerificationError do
+ provider.validate_webhook!(token, "{}")
+ end
+ end
+
+ test "rejects webhook tokens whose body hash does not match the raw body" do
+ provider, jwk, key, body = verified_webhook_setup
+ token = JWT.encode(
+ { iat: Time.current.to_i, request_body_sha256: Digest::SHA256.hexdigest(body) },
+ key, "ES256", { "kid" => jwk.kid }
+ )
+
+ assert_raises JWT::VerificationError do
+ provider.validate_webhook!(token, body + " ")
+ end
+ end
+
+ test "rejects webhook tokens issued more than five minutes ago" do
+ provider, jwk, key, body = verified_webhook_setup
+ token = JWT.encode(
+ { iat: 6.minutes.ago.to_i, request_body_sha256: Digest::SHA256.hexdigest(body) },
+ key, "ES256", { "kid" => jwk.kid }
+ )
+
+ assert_raises JWT::VerificationError do
+ provider.validate_webhook!(token, body)
+ end
+ end
+
+ test "rejects webhook tokens signed with an unsupported algorithm" do
+ provider, jwk, _key, body = verified_webhook_setup(require_key_fetch: false)
+
+ token = JWT.encode(
+ { iat: Time.current.to_i, request_body_sha256: Digest::SHA256.hexdigest(body) },
+ "not-a-real-secret", "HS256", { "kid" => jwk.kid }
+ )
+
+ assert_raises JWT::VerificationError, JWT::DecodeError do
+ provider.validate_webhook!(token, body)
+ end
+ end
+
+ test "accepts a token with an expired exp while the iat age check governs freshness" do
+ provider, jwk, key, body = verified_webhook_setup
+ token = JWT.encode(
+ { iat: Time.current.to_i, exp: 1.minute.ago.to_i, request_body_sha256: Digest::SHA256.hexdigest(body) },
+ key, "ES256", { "kid" => jwk.kid }
+ )
+
+ assert_nothing_raised { provider.validate_webhook!(token, body) }
+ end
+
private
+ # Pins the webhook verification contract that the jwt gem bump (2.10.3 ->
+ # 3.3.0) rides on: JWKS built from the key Plaid publishes for the token's
+ # kid, ES256 decode with expiration skipped in favor of the iat age check,
+ # and the request-body SHA-256 comparison.
+ def verified_webhook_setup(require_key_fetch: true)
+ key = OpenSSL::PKey::EC.generate("prime256v1")
+ jwk = JWT::JWK.new(key, { use: "sig" })
+ body = '{"webhook_type":"TRANSACTIONS","webhook_code":"INITIAL_UPDATE"}'
+
+ client = mock
+ if require_key_fetch
+ client.expects(:webhook_verification_key_get).with do |request|
+ request.is_a?(Plaid::WebhookVerificationKeyGetRequest) && request.key_id == jwk.kid
+ end.returns(Struct.new(:key).new(jwk.export))
+ else
+ # An unsupported algorithm is rejected at decode time, before any
+ # key fetch happens.
+ client.stubs(:webhook_verification_key_get)
+ end
+
+ config = Plaid::Configuration.new
+ config.server_index = Plaid::Configuration::Environment["sandbox"]
+ provider = Provider::Plaid.new(config)
+ provider.instance_variable_set(:@client, client)
+
+ [ provider, jwk, key, body ]
+ end
+
def get_access_token
VCR.use_cassette("plaid/access_token") do
public_token = @plaid.create_public_token
diff --git a/test/models/web_push/client_test.rb b/test/models/web_push/client_test.rb
new file mode 100644
index 0000000000..ce039abb3c
--- /dev/null
+++ b/test/models/web_push/client_test.rb
@@ -0,0 +1,68 @@
+require "test_helper"
+require Rails.root.join("test/support/web_push_test_helper")
+
+class WebPushClientTest < ActiveSupport::TestCase
+ include WebPushTestHelper
+
+ setup do
+ @subscription = register_web_push
+ @vapid = { public_key: "test-public-key", private_key: "test-private-key", subject: "mailto:[email protected]" }
+ WebPush::Client.stubs(:vapid).returns(@vapid)
+ end
+
+ test "uses the web push library for standards based encryption and VAPID delivery" do
+ payload = { title: "Sure", body: "A new financial alert is available." }
+ WebPush.expects(:payload_send).with do |options|
+ options[:endpoint] == @subscription.endpoint && options[:p256dh] == @subscription.p256dh &&
+ options[:auth] == @subscription.auth && JSON.parse(options[:message]) == payload.stringify_keys &&
+ options[:vapid] == @vapid && options[:open_timeout].positive? && options[:read_timeout].positive?
+ end.returns(true)
+ assert_equal :accepted, WebPush::Client.new.deliver(subscription: @subscription, payload: payload)
+ end
+
+ test "revalidates persisted endpoints before contacting a provider" do
+ @subscription.update_column(:endpoint, "https://169.254.169.254/latest/meta-data")
+ WebPush.expects(:payload_send).never
+ assert_equal :rejected, WebPush::Client.new.deliver(subscription: @subscription.reload, payload: {})
+ end
+
+ test "network failures have a sanitized transient error" do
+ WebPush.stubs(:payload_send).raises(Net::ReadTimeout, "secret endpoint #{@subscription.endpoint}")
+ error = assert_raises(WebPush::Client::TransientError) do
+ WebPush::Client.new.deliver(subscription: @subscription, payload: {})
+ end
+ assert_not_includes error.message, @subscription.endpoint
+ assert_not_includes error.message, @subscription.auth
+ end
+ test "invalid subscriptions are gone while retryable provider failures are sanitized" do
+ [ WebPush::InvalidSubscription, WebPush::ExpiredSubscription ].each do |error_class|
+ WebPush.stubs(:payload_send).raises(error_class.new(stub(body: "provider details"), "fcm.googleapis.com"))
+ assert_equal :gone, WebPush::Client.new.deliver(subscription: @subscription, payload: {})
+ end
+ [ WebPush::TooManyRequests, WebPush::PushServiceError ].each do |error_class|
+ WebPush.stubs(:payload_send).raises(error_class.new(stub(body: "sensitive provider details"), "fcm.googleapis.com"))
+ error = assert_raises(WebPush::Client::TransientError) do
+ WebPush::Client.new.deliver(subscription: @subscription, payload: {})
+ end
+ assert_not_includes error.message, "sensitive provider details"
+ end
+ end
+
+ test "other provider rejections do not retry or follow redirects" do
+ WebPush.stubs(:payload_send).raises(WebPush::ResponseError.new(stub(body: "redirect or rejection"), "fcm.googleapis.com"))
+ assert_equal :rejected, WebPush::Client.new.deliver(subscription: @subscription, payload: {})
+ end
+
+ test "configuration validates a real VAPID pair and contact URI" do
+ WebPush::Client.unstub(:vapid)
+ key = WebPush.generate_key
+ values = { WEB_PUSH_VAPID_PUBLIC_KEY: key.public_key, WEB_PUSH_VAPID_PRIVATE_KEY: key.private_key,
+ WEB_PUSH_VAPID_SUBJECT: "mailto:[email protected]" }
+ ClimateControl.modify(values) { assert WebPush::Client.configured? }
+ [ { WEB_PUSH_VAPID_PRIVATE_KEY: nil }, { WEB_PUSH_VAPID_PUBLIC_KEY: "invalid" },
+ { WEB_PUSH_VAPID_SUBJECT: "http://example.test" }, { WEB_PUSH_VAPID_SUBJECT: "mailto:" },
+ { WEB_PUSH_VAPID_PRIVATE_KEY: WebPush.generate_key.private_key } ].each do |invalid|
+ ClimateControl.modify(values.merge(invalid)) { assert_not WebPush::Client.configured? }
+ end
+ end
+end
diff --git a/test/models/web_push_subscription_test.rb b/test/models/web_push_subscription_test.rb
new file mode 100644
index 0000000000..31f0586b5f
--- /dev/null
+++ b/test/models/web_push_subscription_test.rb
@@ -0,0 +1,156 @@
+require "test_helper"
+require Rails.root.join("test/support/web_push_test_helper")
+
+class WebPushSubscriptionTest < ActiveSupport::TestCase
+ include WebPushTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @session = @user.sessions.create!
+ @attributes = web_push_attributes
+ end
+
+ test "updates the current session registration without duplicating it" do
+ first = WebPushSubscription.register_for!(user: @user, session: @session, **@attributes)
+ assert_no_difference "WebPushSubscription.count" do
+ second = WebPushSubscription.register_for!(user: @user, session: @session, **@attributes)
+ assert_equal first.id, second.id
+ end
+ assert_equal @session.id, first.session_id
+ assert_equal Digest::SHA256.hexdigest(@attributes[:endpoint]), first.endpoint_digest
+ end
+
+ test "endpoint knowledge alone cannot steal another user's registration" do
+ original = register_web_push(**@attributes)
+ other_user = users(:family_member)
+ assert_raises ActiveRecord::RecordInvalid do
+ register_web_push(user: other_user, endpoint: @attributes[:endpoint])
+ end
+ assert_equal @user.id, original.reload.user_id
+ end
+
+ test "proof of both subscription keys replaces the old row when the browser changes users" do
+ original = register_web_push(**@attributes)
+ other_user = users(:family_member)
+ replacement = register_web_push(user: other_user, **@attributes)
+ assert_not_equal original.id, replacement.id
+ assert_not WebPushSubscription.exists?(original.id)
+ assert_equal other_user.id, replacement.user_id
+ end
+
+ test "key proof is matched on the decoded bytes, across equivalent Base64 encodings" do
+ original = register_web_push(**@attributes)
+ assert original.matches_keys?(@attributes[:p256dh], @attributes[:auth])
+ assert original.matches_keys?(@attributes[:p256dh] + "=", @attributes[:auth] + "==")
+ assert_not original.matches_keys?(@attributes[:p256dh], web_push_attributes[:auth] + "==")
+ assert_not original.matches_keys?("nonsense", @attributes[:auth])
+ assert_not original.matches_keys?(nil, @attributes[:auth])
+ end
+
+ test "padded Base64 proof across users replaces the old row instead of colliding" do
+ original = register_web_push(**@attributes)
+ other_user = users(:family_member)
+ replacement = register_web_push(user: other_user, endpoint: @attributes[:endpoint],
+ p256dh: @attributes[:p256dh] + "=", auth: @attributes[:auth] + "==")
+ assert_not_equal original.id, replacement.id
+ assert_not WebPushSubscription.exists?(original.id)
+ assert_equal other_user.id, replacement.user_id
+ end
+
+ test "a new session replaces the old registration even for the same user" do
+ original = WebPushSubscription.register_for!(user: @user, session: @session, **@attributes)
+ replacement = register_web_push(**@attributes)
+ assert_not_equal original.id, replacement.id
+ assert_not WebPushSubscription.exists?(original.id)
+ end
+
+ test "rejects sessions belonging to another user" do
+ assert_raises ActiveRecord::RecordInvalid do
+ WebPushSubscription.register_for!(user: users(:family_member), session: @session, **@attributes)
+ end
+ end
+
+ test "accepts the supported browser push services" do
+ %w[https://web.push.apple.com/Q https://fcm.googleapis.com/fcm/send/Q https://updates.push.services.mozilla.com/wpush/v2/Q https://wns2-db5p.notify.windows.com/w/Q].each do |endpoint|
+ assert register_web_push(endpoint: endpoint).persisted?, endpoint
+ end
+ end
+
+ test "rejects non-public or unrecognized endpoint destinations" do
+ %w[http://fcm.googleapis.com/Q https://localhost/Q https://127.0.0.1/Q https://169.254.169.254/Q https://fcm.googleapis.com.evil.test/Q https://evilpush.apple.com/Q https://push.apple.com.evil.test/Q https://fcm.googleapis.com:8443/Q https://[email protected]/Q https://fcm.googleapis.com/Q#fragment https://example.org/Q].each do |endpoint|
+ assert_raises(ActiveRecord::RecordInvalid, endpoint) { register_web_push(endpoint: endpoint) }
+ end
+ assert_raises(ActiveRecord::RecordInvalid) { register_web_push(endpoint: "https://fcm.googleapis.com/" + "a" * 4096) }
+ end
+
+ test "rejects invalid lengths encodings and off-curve public keys" do
+ [ { p256dh: "!" * 87 }, { p256dh: Base64.urlsafe_encode64("\x04" + "\x00" * 64, padding: false) },
+ { p256dh: Base64.urlsafe_encode64("a" * 33, padding: false) }, { auth: "x" * 22 },
+ { auth: Base64.urlsafe_encode64("a" * 15, padding: false) }, { auth: "a" * 1000 } ].each do |invalid|
+ assert_raises(ActiveRecord::RecordInvalid) { register_web_push(**@attributes.merge(invalid)) }
+ end
+ end
+
+ test "revoked and expired sessions cannot receive notifications" do
+ subscription = WebPushSubscription.register_for!(user: @user, session: @session, **@attributes)
+ assert subscription.eligible?
+ @session.update_columns(updated_at: 31.days.ago)
+ assert_not subscription.reload.eligible?
+ @session.touch
+ @session.destroy!
+ assert_not WebPushSubscription.exists?(subscription.id)
+ end
+
+ test "registration secrets are filtered from request logs" do
+ filtered = ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters).filter(@attributes.stringify_keys)
+ assert_equal "[FILTERED]", filtered["endpoint"]
+ assert_equal "[FILTERED]", filtered["p256dh"]
+ assert_equal "[FILTERED]", filtered["auth"]
+ end
+ test "equivalent host case and default port share one canonical endpoint identity" do
+ original = register_web_push(**@attributes)
+ equivalent = @attributes.merge(endpoint: @attributes[:endpoint].sub("fcm.googleapis.com", "FCM.GOOGLEAPIS.COM:443"))
+ assert_no_difference "WebPushSubscription.count" do
+ renewed = WebPushSubscription.register_for!(user: @user, session: original.session, **equivalent)
+ assert_equal original.id, renewed.id
+ assert_equal @attributes[:endpoint], renewed.endpoint
+ end
+ assert_raises ActiveRecord::RecordInvalid do
+ register_web_push(user: users(:family_member), endpoint: equivalent[:endpoint])
+ end
+ end
+
+ test "caps registrations per user while permitting renewal and session replacement" do
+ devices = 20.times.map { |i| register_web_push(user: @user, session: @session, endpoint: "https://fcm.googleapis.com/device-#{i}") }
+ assert_raises ActiveRecord::RecordInvalid do
+ register_web_push(user: @user, endpoint: "https://fcm.googleapis.com/device-excess")
+ end
+ original = devices.first
+ assert_no_difference "WebPushSubscription.count" do
+ renewed = WebPushSubscription.register_for!(user: @user, session: @session,
+ endpoint: original.endpoint, p256dh: original.p256dh, auth: original.auth)
+ assert_equal original.id, renewed.id
+ replacement = register_web_push(user: @user,
+ endpoint: original.endpoint, p256dh: original.p256dh, auth: original.auth)
+ assert_not_equal original.id, replacement.id
+ end
+ assert register_web_push(user: users(:family_member), endpoint: "https://fcm.googleapis.com/another-user").persisted?
+ end
+
+ test "test notification requests are throttled per device with a cooldown" do
+ subscription = WebPushSubscription.register_for!(user: @user, session: @session, **@attributes)
+ first = subscription.request_test_notification!
+ assert first.persisted?
+ assert_equal subscription.id, first.subscription_id
+
+ travel WebPushSubscription::TEST_NOTIFICATION_COOLDOWN - 1.second do
+ assert_nil subscription.request_test_notification!
+ end
+
+ travel WebPushSubscription::TEST_NOTIFICATION_COOLDOWN + 1.second do
+ second = subscription.request_test_notification!
+ assert second.persisted?
+ assert_not_equal first.id, second.id
+ end
+ end
+end
diff --git a/test/support/web_push_test_helper.rb b/test/support/web_push_test_helper.rb
new file mode 100644
index 0000000000..ce8538aacb
--- /dev/null
+++ b/test/support/web_push_test_helper.rb
@@ -0,0 +1,21 @@
+require "openssl"
+require "base64"
+
+module WebPushTestHelper
+ def web_push_attributes(endpoint: "https://fcm.googleapis.com/fcm/send/test-device")
+ {
+ endpoint: endpoint,
+ p256dh: Base64.urlsafe_encode64(OpenSSL::PKey::EC.generate("prime256v1").public_key.to_octet_string(:uncompressed), padding: false),
+ auth: Base64.urlsafe_encode64(SecureRandom.random_bytes(16), padding: false)
+ }
+ end
+
+ def register_web_push(user: users(:family_admin), session: nil, **attributes)
+ session ||= user.sessions.create!
+ WebPushSubscription.register_for!(user: user, session: session, **web_push_attributes.merge(attributes))
+ end
+
+ def enable_web_push_preview(user)
+ user.update!(preferences: user.preferences.merge("preview_features_enabled" => true))
+ end
+end
diff --git a/test/system/web_push_notifications_test.rb b/test/system/web_push_notifications_test.rb
new file mode 100644
index 0000000000..752d7f494e
--- /dev/null
+++ b/test/system/web_push_notifications_test.rb
@@ -0,0 +1,98 @@
+require "application_system_test_case"
+require Rails.root.join("test/support/web_push_test_helper")
+
+class WebPushNotificationsTest < ApplicationSystemTestCase
+ include WebPushTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ enable_web_push_preview(@user)
+ WebPush::Client.stubs(:configured?).returns(true)
+ WebPush::Client.stubs(:vapid).returns(public_key: Base64.urlsafe_encode64("a" * 65, padding: false))
+ sign_in @user
+ end
+
+ test "explicit device controls register test and remove only this browser" do
+ attributes = web_push_attributes
+ visit settings_preferences_path
+ assert_selector "[data-controller='web-push']"
+ install_browser_push_double(attributes)
+
+ assert_equal 0, page.evaluate_script("window.pushTest.permissionRequests")
+ click_on I18n.t("web_push.enable")
+ assert_text I18n.t("web_push.status.enabled")
+ assert_equal 1, page.evaluate_script("window.pushTest.permissionRequests")
+ device = @user.web_push_subscriptions.find_by!(endpoint_digest: Digest::SHA256.hexdigest(attributes[:endpoint]))
+
+ click_on I18n.t("web_push.test")
+ assert_text I18n.t("web_push.status.queued")
+ delivery = device.push_deliveries.where(insight_id: nil).last!
+ client = mock
+ WebPush::Client.expects(:new).returns(client)
+ client.expects(:deliver).returns(:accepted)
+ DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)
+ assert_text I18n.t("web_push.status.accepted"), wait: 10
+ capture_notification_card
+
+ click_on I18n.t("web_push.disable")
+ assert_text I18n.t("web_push.status.disabled")
+ assert_not WebPushSubscription.exists?(device.id)
+ assert_equal true, page.evaluate_script("window.pushTest.unsubscribed")
+ end
+
+ test "budget warning opt in is saved independently from device registration" do
+ visit settings_preferences_path
+ find("#user_push_budget_warnings_enabled + label").click
+ assert_selector "#user_push_budget_warnings_enabled[checked]"
+ assert @user.reload.push_budget_warnings_enabled?
+ assert_empty @user.web_push_subscriptions
+ end
+
+ private
+ def capture_notification_card
+ card = "[data-controller='web-push']"
+ find(card).native.save_screenshot(Rails.root.join("tmp", "web-push-notifications-desktop.png"))
+ page.current_window.resize_to(390, 844)
+ find(card).native.save_screenshot(Rails.root.join("tmp", "web-push-notifications-mobile.png"))
+ ensure
+ reset_viewport
+ end
+
+ # Browser/OS push permission is outside Selenium's portable API. Replace that
+ # boundary only; clicks, CSRF, Rails registration, status polling and deletion
+ # still use the real application. This does not prove phone presentation.
+ def install_browser_push_double(attributes)
+ script = <<~JS
+ const attributes = arguments[0];
+ const complete = arguments[arguments.length - 1];
+ const element = document.querySelector('[data-controller="web-push"]');
+ const controller = window.Stimulus.getControllerForElementAndIdentifier(element, "web-push");
+ window.pushTest = { permissionRequests: 0, unsubscribed: false, current: null };
+ const device = {
+ toJSON: () => ({ endpoint: attributes.endpoint, keys: { p256dh: attributes.p256dh, auth: attributes.auth } }),
+ unsubscribe: async () => { window.pushTest.unsubscribed = true; window.pushTest.current = null; return true; }
+ };
+ const registration = { pushManager: {
+ getSubscription: async () => window.pushTest.current,
+ subscribe: async (options) => {
+ device.options = { applicationServerKey: options.applicationServerKey.buffer };
+ window.pushTest.current = device;
+ return device;
+ }
+ } };
+ Object.defineProperty(window, "isSecureContext", { configurable: true, value: true });
+ Object.defineProperty(window, "PushManager", { configurable: true, value: function() {} });
+ Object.defineProperty(window, "Notification", { configurable: true, value: {
+ permission: "default",
+ requestPermission: async () => { window.pushTest.permissionRequests++; window.Notification.permission = "granted"; return "granted"; }
+ } });
+ Object.defineProperty(navigator, "serviceWorker", { configurable: true, value: {
+ getRegistration: async () => registration,
+ register: async () => registration,
+ ready: Promise.resolve(registration)
+ } });
+ controller.connect().then(complete);
+ JS
+ page.driver.browser.execute_async_script(script, attributes.stringify_keys)
+ end
+end