The personal finance app for everyone (by everyone)
Ruby
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