pezza_action_push_web 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e6874f14504ef40025713d4b82b955e135845182a3629899a976ab3e665fe397
4
- data.tar.gz: 4b2e90aefaafd63951bc527f86c122951c8a50704d2e0f9fca010d1630c25543
3
+ metadata.gz: 2b38a01863916f285ea98b99ea79483767c4633bc1bf51a54c232703260e947c
4
+ data.tar.gz: e0cad328df4292a41a013554ff90176b8fe34baaaf77477a03e26620ae7e0075
5
5
  SHA512:
6
- metadata.gz: 4b84140a676d8c9ced3c23b343bf0ff306c9a3619042a7ab23320111791011a8f20cfdc2438a51ed00be743b3eae2962d2a202db82cdd2496f3c83704534977a
7
- data.tar.gz: 07df39534c92844a589e922fb017165e259f65f7d12b3ba0b21fc173de3243a36a1556a2866cedd5c9b0a1669d992fe5bf674b7c8e2cbd1d5880830c660095b7
6
+ metadata.gz: 1f8cc2f332367bfef4d89b06864379447337e09ae825354aa712de31c863d3b2b5ea90451cab640aca6756b4808bb013f9afe8572d258c3288b097b38d5e8418
7
+ data.tar.gz: 151514426c7a3218ada6b191a8fe917364d7a571577ec9d0b1174cb0d73e2b0cc3a91182dfabfa23934823879ab7d1a0dcdd409a1eb3b074b9ed85f1c7c108c5
data/README.md CHANGED
@@ -26,7 +26,6 @@ The installation will create:
26
26
  - `app/views/pwa/service_worker.js`
27
27
  - mount the subscriptions controllers
28
28
  - import action_push_web.js in your application.js
29
- - Add `<%= action_push_web_key_tag %>` to the <head> of your application's layout if it can find it. Otherwise, you'll need to add it manually.
30
29
 
31
30
 
32
31
  `app/models/application_push_web_notification.rb`:
@@ -94,8 +93,8 @@ shared:
94
93
  # Change the subject (default: mailto:sender@example.com).
95
94
  # expiration: mailto:support@my-domain.com
96
95
 
97
- # Change the urgency (default: normal). You also choose to set this at the notification level.
98
- # urgency: high
96
+ # Change the urgency (default: high). You also choose to set this at the notification level.
97
+ # urgency: normal
99
98
  ```
100
99
 
101
100
  This file contains the configuration for the push notification services you want to use.
@@ -10,11 +10,6 @@ class Request extends HTMLElement {
10
10
  this.addEventListener("click", this.onClick);
11
11
  }
12
12
  #setState() {
13
- if (this.isEnabled) {
14
- this.removeAttribute("disabled");
15
- } else {
16
- this.setAttribute("disabled", true);
17
- }
18
13
  this.hidden = !this.isEnabled;
19
14
  }
20
15
  disconnectedCallback() {
@@ -24,15 +19,12 @@ class Request extends HTMLElement {
24
19
  this.#setState();
25
20
  }
26
21
  get isEnabled() {
27
- return navigator.serviceWorker && window.Notification && Notification.permission == "default" && this.getAttribute("href");
28
- }
29
- get #isDisabled() {
30
- return this.hasAttribute("disabled");
22
+ return navigator.serviceWorker && window.Notification && Notification.permission == "default";
31
23
  }
32
24
  async onClick(event) {
33
25
  event.preventDefault();
34
26
  event.stopPropagation();
35
- if (this.isEnabled && !this.isDisabled) {
27
+ if (this.isEnabled) {
36
28
  const permission = await Notification.requestPermission();
37
29
  if (permission === "granted") {
38
30
  document.dispatchEvent(new CustomEvent("action-push-web:granted", {}));
@@ -66,292 +58,6 @@ class Denied extends HTMLElement {
66
58
  }
67
59
  }
68
60
 
69
- // node_modules/@rails/request.js/src/fetch_response.js
70
- class FetchResponse {
71
- constructor(response) {
72
- this.response = response;
73
- }
74
- get statusCode() {
75
- return this.response.status;
76
- }
77
- get redirected() {
78
- return this.response.redirected;
79
- }
80
- get ok() {
81
- return this.response.ok;
82
- }
83
- get unauthenticated() {
84
- return this.statusCode === 401;
85
- }
86
- get unprocessableEntity() {
87
- return this.statusCode === 422;
88
- }
89
- get authenticationURL() {
90
- return this.response.headers.get("WWW-Authenticate");
91
- }
92
- get contentType() {
93
- const contentType = this.response.headers.get("Content-Type") || "";
94
- return contentType.replace(/;.*$/, "");
95
- }
96
- get headers() {
97
- return this.response.headers;
98
- }
99
- get html() {
100
- if (this.contentType.match(/^(application|text)\/(html|xhtml\+xml)$/)) {
101
- return this.text;
102
- }
103
- return Promise.reject(new Error(`Expected an HTML response but got "${this.contentType}" instead`));
104
- }
105
- get json() {
106
- if (this.contentType.match(/^application\/.*json$/)) {
107
- return this.responseJson || (this.responseJson = this.response.json());
108
- }
109
- return Promise.reject(new Error(`Expected a JSON response but got "${this.contentType}" instead`));
110
- }
111
- get text() {
112
- return this.responseText || (this.responseText = this.response.text());
113
- }
114
- get isTurboStream() {
115
- return this.contentType.match(/^text\/vnd\.turbo-stream\.html/);
116
- }
117
- get isScript() {
118
- return this.contentType.match(/\b(?:java|ecma)script\b/);
119
- }
120
- async renderTurboStream() {
121
- if (this.isTurboStream) {
122
- if (window.Turbo) {
123
- await window.Turbo.renderStreamMessage(await this.text);
124
- } else {
125
- console.warn("You must set `window.Turbo = Turbo` to automatically process Turbo Stream events with request.js");
126
- }
127
- } else {
128
- return Promise.reject(new Error(`Expected a Turbo Stream response but got "${this.contentType}" instead`));
129
- }
130
- }
131
- async activeScript() {
132
- if (this.isScript) {
133
- const script = document.createElement("script");
134
- const metaTag = document.querySelector("meta[name=csp-nonce]");
135
- if (metaTag) {
136
- const nonce = metaTag.nonce === "" ? metaTag.content : metaTag.nonce;
137
- if (nonce) {
138
- script.setAttribute("nonce", nonce);
139
- }
140
- }
141
- script.innerHTML = await this.text;
142
- document.body.appendChild(script);
143
- } else {
144
- return Promise.reject(new Error(`Expected a Script response but got "${this.contentType}" instead`));
145
- }
146
- }
147
- }
148
-
149
- // node_modules/@rails/request.js/src/request_interceptor.js
150
- class RequestInterceptor {
151
- static register(interceptor) {
152
- this.interceptor = interceptor;
153
- }
154
- static get() {
155
- return this.interceptor;
156
- }
157
- static reset() {
158
- this.interceptor = undefined;
159
- }
160
- }
161
-
162
- // node_modules/@rails/request.js/src/lib/utils.js
163
- function getCookie(name) {
164
- const cookies = document.cookie ? document.cookie.split("; ") : [];
165
- const prefix = `${encodeURIComponent(name)}=`;
166
- const cookie = cookies.find((cookie2) => cookie2.startsWith(prefix));
167
- if (cookie) {
168
- const value = cookie.split("=").slice(1).join("=");
169
- if (value) {
170
- return decodeURIComponent(value);
171
- }
172
- }
173
- }
174
- function compact(object) {
175
- const result = {};
176
- for (const key in object) {
177
- const value = object[key];
178
- if (value !== undefined) {
179
- result[key] = value;
180
- }
181
- }
182
- return result;
183
- }
184
- function metaContent(name) {
185
- const element = document.head.querySelector(`meta[name="${name}"]`);
186
- return element && element.content;
187
- }
188
- function stringEntriesFromFormData(formData) {
189
- return [...formData].reduce((entries, [name, value]) => {
190
- return entries.concat(typeof value === "string" ? [[name, value]] : []);
191
- }, []);
192
- }
193
- function mergeEntries(searchParams, entries) {
194
- for (const [name, value] of entries) {
195
- if (value instanceof window.File)
196
- continue;
197
- if (searchParams.has(name) && !name.includes("[]")) {
198
- searchParams.delete(name);
199
- searchParams.set(name, value);
200
- } else {
201
- searchParams.append(name, value);
202
- }
203
- }
204
- }
205
-
206
- // node_modules/@rails/request.js/src/fetch_request.js
207
- class FetchRequest {
208
- constructor(method, url, options = {}) {
209
- this.method = method;
210
- this.options = options;
211
- this.originalUrl = url.toString();
212
- }
213
- async perform() {
214
- try {
215
- const requestInterceptor = RequestInterceptor.get();
216
- if (requestInterceptor) {
217
- await requestInterceptor(this);
218
- }
219
- } catch (error) {
220
- console.error(error);
221
- }
222
- const fetch = this.responseKind === "turbo-stream" && window.Turbo ? window.Turbo.fetch : window.fetch;
223
- const response = new FetchResponse(await fetch(this.url, this.fetchOptions));
224
- if (response.unauthenticated && response.authenticationURL) {
225
- return Promise.reject(window.location.href = response.authenticationURL);
226
- }
227
- if (response.isScript) {
228
- await response.activeScript();
229
- }
230
- const responseStatusIsTurboStreamable = response.ok || response.unprocessableEntity;
231
- if (responseStatusIsTurboStreamable && response.isTurboStream) {
232
- await response.renderTurboStream();
233
- }
234
- return response;
235
- }
236
- addHeader(key, value) {
237
- const headers = this.additionalHeaders;
238
- headers[key] = value;
239
- this.options.headers = headers;
240
- }
241
- sameHostname() {
242
- if (!this.originalUrl.startsWith("http:") && !this.originalUrl.startsWith("https:")) {
243
- return true;
244
- }
245
- try {
246
- return new URL(this.originalUrl).hostname === window.location.hostname;
247
- } catch (_) {
248
- return true;
249
- }
250
- }
251
- get fetchOptions() {
252
- return {
253
- method: this.method.toUpperCase(),
254
- headers: this.headers,
255
- body: this.formattedBody,
256
- signal: this.signal,
257
- credentials: this.credentials,
258
- redirect: this.redirect,
259
- keepalive: this.keepalive
260
- };
261
- }
262
- get headers() {
263
- const baseHeaders = {
264
- "X-Requested-With": "XMLHttpRequest",
265
- "Content-Type": this.contentType,
266
- Accept: this.accept
267
- };
268
- if (this.sameHostname()) {
269
- baseHeaders["X-CSRF-Token"] = this.csrfToken;
270
- }
271
- return compact(Object.assign(baseHeaders, this.additionalHeaders));
272
- }
273
- get csrfToken() {
274
- return getCookie(metaContent("csrf-param")) || metaContent("csrf-token");
275
- }
276
- get contentType() {
277
- if (this.options.contentType) {
278
- return this.options.contentType;
279
- } else if (this.body == null || this.body instanceof window.FormData) {
280
- return;
281
- } else if (this.body instanceof window.File) {
282
- return this.body.type;
283
- }
284
- return "application/json";
285
- }
286
- get accept() {
287
- switch (this.responseKind) {
288
- case "html":
289
- return "text/html, application/xhtml+xml";
290
- case "turbo-stream":
291
- return "text/vnd.turbo-stream.html, text/html, application/xhtml+xml";
292
- case "json":
293
- return "application/json, application/vnd.api+json";
294
- case "script":
295
- return "text/javascript, application/javascript";
296
- default:
297
- return "*/*";
298
- }
299
- }
300
- get body() {
301
- return this.options.body;
302
- }
303
- get query() {
304
- const originalQuery = (this.originalUrl.split("?")[1] || "").split("#")[0];
305
- const params = new URLSearchParams(originalQuery);
306
- let requestQuery = this.options.query;
307
- if (requestQuery instanceof window.FormData) {
308
- requestQuery = stringEntriesFromFormData(requestQuery);
309
- } else if (requestQuery instanceof window.URLSearchParams) {
310
- requestQuery = requestQuery.entries();
311
- } else {
312
- requestQuery = Object.entries(requestQuery || {});
313
- }
314
- mergeEntries(params, requestQuery);
315
- const query = params.toString();
316
- return query.length > 0 ? `?${query}` : "";
317
- }
318
- get url() {
319
- return this.originalUrl.split("?")[0].split("#")[0] + this.query;
320
- }
321
- get responseKind() {
322
- return this.options.responseKind || "html";
323
- }
324
- get signal() {
325
- return this.options.signal;
326
- }
327
- get redirect() {
328
- return this.options.redirect || "follow";
329
- }
330
- get credentials() {
331
- return this.options.credentials || "same-origin";
332
- }
333
- get keepalive() {
334
- return this.options.keepalive || false;
335
- }
336
- get additionalHeaders() {
337
- return this.options.headers || {};
338
- }
339
- get formattedBody() {
340
- const bodyIsAString = Object.prototype.toString.call(this.body) === "[object String]";
341
- const contentTypeIsJson = this.headers["Content-Type"] === "application/json";
342
- if (contentTypeIsJson && !bodyIsAString) {
343
- return JSON.stringify(this.body);
344
- }
345
- return this.body;
346
- }
347
- }
348
-
349
- // node_modules/@rails/request.js/src/verbs.js
350
- async function post(url, options) {
351
- const request = new FetchRequest("post", url, options);
352
- return request.perform();
353
- }
354
-
355
61
  // app/assets/javascripts/components/granted.js
356
62
  class Granted extends HTMLElement {
357
63
  constructor() {
@@ -376,22 +82,26 @@ class Granted extends HTMLElement {
376
82
  });
377
83
  }
378
84
  get #isEnabled() {
379
- return !!navigator.serviceWorker && !!window.Notification && Notification.permission == "granted";
85
+ return !!navigator.serviceWorker && !!window.Notification && Notification.permission == "granted" && this.getAttribute("href") && this.getAttribute("public-key");
380
86
  }
381
87
  get #serviceWorkerRegistration() {
382
88
  return navigator.serviceWorker.getRegistration();
383
89
  }
384
90
  get #vapidPublicKey() {
385
- const encodedVapidPublicKey = document.querySelector('meta[name="action-push-web-public-key"]').content;
386
- return this.#urlBase64ToUint8Array(encodedVapidPublicKey);
91
+ return this.#urlBase64ToUint8Array(this.getAttribute("public-key"));
387
92
  }
388
93
  async#syncPushSubscription(subscription) {
389
- const response = await post(this.getAttribute("href"), {
390
- body: this.#extractJsonPayloadAsString(subscription)
94
+ const response = await fetch(this.getAttribute("href"), {
95
+ method: "POST",
96
+ body: this.#extractJsonPayloadAsString(subscription),
97
+ headers: {
98
+ Accept: "text/vnd.turbo-stream.html, text/html, application/xhtml+xml",
99
+ "Content-Type": "application/json",
100
+ "X-CSRF-Token": document.querySelector("meta[name=csrf-token]").content
101
+ }
391
102
  });
392
- if (!response.ok) {
103
+ if (!response.ok)
393
104
  subscription.unsubscribe();
394
- }
395
105
  }
396
106
  #extractJsonPayloadAsString(subscription) {
397
107
  const { endpoint, keys: { p256dh, auth } } = subscription.toJSON();
@@ -1,5 +1,3 @@
1
- import { post } from "@rails/request.js"
2
-
3
1
  export default class Granted extends HTMLElement {
4
2
  constructor() {
5
3
  super();
@@ -30,7 +28,7 @@ export default class Granted extends HTMLElement {
30
28
  }
31
29
 
32
30
  get #isEnabled() {
33
- return !!navigator.serviceWorker && !!window.Notification && Notification.permission == "granted"
31
+ return !!navigator.serviceWorker && !!window.Notification && Notification.permission == "granted" && this.getAttribute('href') && this.getAttribute('public-key')
34
32
  }
35
33
 
36
34
  get #serviceWorkerRegistration() {
@@ -38,18 +36,20 @@ export default class Granted extends HTMLElement {
38
36
  }
39
37
 
40
38
  get #vapidPublicKey() {
41
- const encodedVapidPublicKey = document.querySelector('meta[name="action-push-web-public-key"]').content
42
- return this.#urlBase64ToUint8Array(encodedVapidPublicKey)
39
+ return this.#urlBase64ToUint8Array(this.getAttribute('public-key'))
43
40
  }
44
41
 
45
42
  async #syncPushSubscription(subscription) {
46
- const response = await post(this.getAttribute('href'), {
43
+ const response = await fetch(this.getAttribute('href'), {
44
+ method: "POST",
47
45
  body: this.#extractJsonPayloadAsString(subscription),
46
+ headers: {
47
+ Accept: "text/vnd.turbo-stream.html, text/html, application/xhtml+xml",
48
+ "Content-Type": "application/json",
49
+ "X-CSRF-Token": document.querySelector("meta[name=csrf-token]").content
50
+ }
48
51
  })
49
-
50
- if (!response.ok) {
51
- subscription.unsubscribe()
52
- }
52
+ if (!response.ok) subscription.unsubscribe()
53
53
  }
54
54
 
55
55
  #extractJsonPayloadAsString(subscription) {
@@ -13,12 +13,6 @@ export default class Request extends HTMLElement {
13
13
  }
14
14
 
15
15
  #setState() {
16
- if (this.isEnabled) {
17
- this.removeAttribute('disabled')
18
- } else {
19
- this.setAttribute('disabled', true)
20
- }
21
-
22
16
  this.hidden = !this.isEnabled;
23
17
  }
24
18
 
@@ -31,18 +25,14 @@ export default class Request extends HTMLElement {
31
25
  }
32
26
 
33
27
  get isEnabled() {
34
- return navigator.serviceWorker && window.Notification && Notification.permission == "default" && this.getAttribute('href')
35
- }
36
-
37
- get #isDisabled() {
38
- return this.hasAttribute('disabled')
28
+ return navigator.serviceWorker && window.Notification && Notification.permission == "default"
39
29
  }
40
30
 
41
31
  async onClick(event) {
42
32
  event.preventDefault();
43
33
  event.stopPropagation();
44
34
 
45
- if (this.isEnabled && !this.isDisabled) {
35
+ if (this.isEnabled) {
46
36
  const permission = await Notification.requestPermission()
47
37
  if (permission === "granted") {
48
38
  document.dispatchEvent(new CustomEvent('action-push-web:granted', {}))
@@ -1,11 +1,8 @@
1
1
  module ActionPushWeb
2
2
  class SubscriptionsController < ApplicationController
3
3
  def create
4
- if subscription = ApplicationPushSubscription.find_by(push_subscription_params)
5
- subscription.touch
6
- else
7
- ApplicationPushSubscription.create! push_subscription_params.merge(user_agent: request.user_agent)
8
- end
4
+ ApplicationPushSubscription.create_with(user_agent: request.user_agent).
5
+ create_or_find_by!(push_subscription_params)
9
6
 
10
7
  head :ok
11
8
  end
@@ -1,18 +1,14 @@
1
1
  module ActionPushWeb
2
2
  module ApplicationHelper
3
- def action_push_web_key_tag(application: nil)
4
- tag.meta name: "action-push-web-public-key",
5
- content: ActionPushWeb.config_for(application)[:public_key]
6
- end
7
-
8
3
  def when_web_notifications_disabled(**attrs, &block)
9
4
  content_tag("action-push-web-denied", capture(&block), **attrs)
10
5
  end
11
6
 
12
7
  def when_web_notifications_allowed(href: action_push_web.subscriptions_path,
13
- service_worker_url: pwa_service_worker_path(format: :js), **attrs, &block)
8
+ service_worker_url: pwa_service_worker_path(format: :js), application: nil, **attrs, &block)
14
9
  content_tag("action-push-web-granted", capture(&block),
15
- href:, service_worker_url:, **attrs)
10
+ href:, "service-worker-url" => service_worker_url,
11
+ "public-key" => ActionPushWeb.config_for(application)[:public_key], **attrs)
16
12
  end
17
13
 
18
14
  def ask_for_web_notifications(**attrs, &block)
@@ -0,0 +1,52 @@
1
+ module ActionPushWeb
2
+ module SsrfProtection
3
+ extend self
4
+
5
+ DNS_RESOLUTION_TIMEOUT = 2
6
+
7
+ DNS_NAMESERVERS = %w[
8
+ 1.1.1.1
9
+ 8.8.8.8
10
+ ]
11
+
12
+ DISALLOWED_IP_RANGES = [
13
+ IPAddr.new("0.0.0.0/8"), # "This" network (RFC1700)
14
+ IPAddr.new("100.64.0.0/10"), # Carrier-grade NAT (RFC6598)
15
+ IPAddr.new("198.18.0.0/15") # Benchmark testing (RFC2544)
16
+ ].freeze
17
+
18
+ def resolve_public_ip(hostname)
19
+ ip_addresses = resolve_dns(hostname)
20
+ public_ips = ip_addresses.reject { |ip| blocked_address?(ip) }
21
+ public_ips.sort_by { |ipaddr| ipaddr.ipv4? ? 0 : 1 }.first&.to_s
22
+ end
23
+
24
+ def blocked_address?(ip)
25
+ ip = IPAddr.new(ip.to_s) unless ip.is_a?(IPAddr)
26
+
27
+ ip.private? ||
28
+ ip.loopback? ||
29
+ ip.link_local? ||
30
+ ip.ipv4_mapped? ||
31
+ ip.ipv4_compat? ||
32
+ in_disallowed_range?(ip)
33
+ end
34
+
35
+ private
36
+ def resolve_dns(hostname)
37
+ ip_addresses = []
38
+
39
+ Resolv::DNS.open(nameserver: DNS_NAMESERVERS, timeouts: DNS_RESOLUTION_TIMEOUT) do |dns|
40
+ dns.each_address(hostname) do |ip_address|
41
+ ip_addresses << IPAddr.new(ip_address.to_s)
42
+ end
43
+ end
44
+
45
+ ip_addresses
46
+ end
47
+
48
+ def in_disallowed_range?(ip)
49
+ DISALLOWED_IP_RANGES.any? { |range| range.include?(ip) }
50
+ end
51
+ end
52
+ end
@@ -2,12 +2,53 @@ module ActionPushWeb
2
2
  class Subscription < ApplicationRecord
3
3
  include ActiveSupport::Rescuable
4
4
 
5
+ PERMITTED_ENDPOINT_HOSTS = %w[
6
+ jmt17.google.com
7
+ fcm.googleapis.com
8
+ updates.push.services.mozilla.com
9
+ web.push.apple.com
10
+ notify.windows.com
11
+ ].freeze
12
+
5
13
  rescue_from(TokenError) { destroy! }
6
14
 
7
15
  belongs_to :owner, polymorphic: true, optional: true
8
16
 
17
+ validates :endpoint, presence: true
18
+ validate :validate_endpoint_url
19
+
9
20
  def push(notification)
10
21
  ActionPushWeb.push(SubscriptionNotification.new(notification:, subscription: self))
11
22
  end
23
+
24
+ def resolved_endpoint_ip
25
+ return @resolved_endpoint_ip if defined?(@resolved_endpoint_ip)
26
+ @resolved_endpoint_ip = SsrfProtection.resolve_public_ip(endpoint_uri&.host)
27
+ end
28
+
29
+ private
30
+
31
+ def endpoint_uri
32
+ @endpoint_uri ||= URI.parse(endpoint) if endpoint.present?
33
+ rescue URI::InvalidURIError
34
+ nil
35
+ end
36
+
37
+ def validate_endpoint_url
38
+ if endpoint_uri.nil?
39
+ errors.add(:endpoint, "is not a valid URL")
40
+ elsif endpoint_uri.scheme != "https"
41
+ errors.add(:endpoint, "must use HTTPS")
42
+ elsif !permitted_endpoint_host?
43
+ errors.add(:endpoint, "is not a permitted push service")
44
+ elsif resolved_endpoint_ip.nil?
45
+ errors.add(:endpoint, "resolves to a private or invalid IP address")
46
+ end
47
+ end
48
+
49
+ def permitted_endpoint_host?
50
+ host = endpoint_uri&.host&.downcase
51
+ PERMITTED_ENDPOINT_HOSTS.any? { |permitted| host&.end_with?(permitted) }
52
+ end
12
53
  end
13
54
  end
@@ -0,0 +1,6 @@
1
+ class AddUniqueIndex < ActiveRecord::Migration[8.1]
2
+ def change
3
+ add_index :action_push_web_subscriptions,
4
+ [ :owner_type, :owner_id, :endpoint ], unique: true
5
+ end
6
+ end
@@ -0,0 +1,6 @@
1
+ class AddUniqueIndexForNullOwner < ActiveRecord::Migration[8.1]
2
+ def change
3
+ add_index :action_push_web_subscriptions, :endpoint, unique: true,
4
+ where: "owner_id IS NULL AND owner_type IS NULL"
5
+ end
6
+ end
@@ -46,7 +46,7 @@ module ActionPushWeb
46
46
  end
47
47
 
48
48
  def urgency
49
- (@urgency.presence || config.fetch(:urgency, :normal)).to_s
49
+ (@urgency.presence || config.fetch(:urgency, :high)).to_s
50
50
  end
51
51
 
52
52
  def as_json
@@ -10,7 +10,11 @@ module ActionPushWeb
10
10
  it.body = payload
11
11
  end
12
12
 
13
- connection.request(uri, request).tap { handle_response(it) }
13
+ if resolved_endpoint_ip
14
+ pinned_connection.request(request)
15
+ else
16
+ connection.request(uri, request)
17
+ end.tap { handle_response(it) }
14
18
  rescue OpenSSL::OpenSSLError
15
19
  raise TokenError.new
16
20
  end
@@ -20,7 +24,7 @@ module ActionPushWeb
20
24
  attr_reader :config, :notification
21
25
 
22
26
  delegate :title, :body, :icon_path, :path, :silent, :badge, :endpoint, :p256dh_key,
23
- :auth_key, to: :notification
27
+ :auth_key, :resolved_endpoint_ip, to: :notification
24
28
 
25
29
  def message
26
30
  JSON.generate title:, options: { body:, icon: icon_path, silent:, badge:, data: { path: } }
@@ -38,6 +42,13 @@ module ActionPushWeb
38
42
  @uri ||= URI.parse(endpoint)
39
43
  end
40
44
 
45
+ def pinned_connection
46
+ Net::HTTP.new(uri.host, uri.port).tap do |http|
47
+ http.ipaddr = resolved_endpoint_ip
48
+ http.use_ssl = true
49
+ end
50
+ end
51
+
41
52
  def headers
42
53
  headers = {}
43
54
  headers["Content-Type"] = "application/octet-stream"
@@ -8,6 +8,6 @@ module ActionPushWeb
8
8
  attr_reader :notification, :subscription
9
9
 
10
10
  delegate_missing_to :notification
11
- delegate :endpoint, :p256dh_key, :auth_key, to: :subscription
11
+ delegate :endpoint, :p256dh_key, :auth_key, :resolved_endpoint_ip, to: :subscription
12
12
  end
13
13
  end
@@ -1,3 +1,3 @@
1
1
  module ActionPushWeb
2
- VERSION = "0.1.1"
2
+ VERSION = "0.2.0"
3
3
  end
@@ -26,14 +26,6 @@ class ActionPushWeb::InstallGenerator < Rails::Generators::Base
26
26
  # run "yarn add action_push_web"
27
27
  end
28
28
 
29
- if APPLICATION_LAYOUT_PATH.exist?
30
- say "Add action push web meta tag in application layout"
31
- insert_into_file APPLICATION_LAYOUT_PATH.to_s, "\n <%= action_push_web_key_tag %>", before: /\s*<\/head>/
32
- else
33
- say "Default application.html.erb is missing!", :red
34
- say " Add <%= action_push_web_key_tag %> within the <head> tag in your custom layout."
35
- end
36
-
37
29
  rails_command "railties:install:migrations FROM=action_push_web",
38
30
  inline: true
39
31
 
@@ -15,8 +15,8 @@ shared:
15
15
  # Change the subject (default: mailto:sender@example.com).
16
16
  # subject: mailto:support@my-domain.com
17
17
 
18
- # Change the urgency (default: normal). You also choose to set this at the notification level.
19
- # urgency: high
18
+ # Change the urgency (default: high). You also choose to set this at the notification level.
19
+ # urgency: normal
20
20
 
21
21
  # Change the icon path (default: nil). You also choose to set this at the notification level.
22
22
  # icon_path: https://example.com/icon.png
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pezza_action_push_web
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nick Pezza
@@ -112,10 +112,13 @@ files:
112
112
  - app/controllers/action_push_web/subscriptions_controller.rb
113
113
  - app/helpers/action_push_web/application_helper.rb
114
114
  - app/jobs/action_push_web/notification_job.rb
115
+ - app/models/action_push_web/ssrf_protection.rb
115
116
  - app/models/action_push_web/subscription.rb
116
117
  - config/importmap.rb
117
118
  - config/routes.rb
118
119
  - db/migrate/20250907213606_create_action_push_web_subscriptions.rb
120
+ - db/migrate/20251209235643_add_unique_index.rb
121
+ - db/migrate/20260517003340_add_unique_index_for_null_owner.rb
119
122
  - lib/action_push_web.rb
120
123
  - lib/action_push_web/engine.rb
121
124
  - lib/action_push_web/errors.rb
@@ -156,7 +159,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
156
159
  - !ruby/object:Gem::Version
157
160
  version: '0'
158
161
  requirements: []
159
- rubygems_version: 3.7.1
162
+ rubygems_version: 4.0.11
160
163
  specification_version: 4
161
164
  summary: Send push notifications to web apps
162
165
  test_files: []