mobiscroll-connect 1.5.1 → 1.6.1
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 +4 -4
- data/CHANGELOG.md +21 -1
- data/README.md +61 -3
- data/lib/mobiscroll/connect/api_client.rb +7 -2
- data/lib/mobiscroll/connect/client.rb +3 -2
- data/lib/mobiscroll/connect/config.rb +5 -2
- data/lib/mobiscroll/connect/errors.rb +15 -0
- data/lib/mobiscroll/connect/models.rb +64 -3
- data/lib/mobiscroll/connect/resources/auth.rb +52 -1
- data/lib/mobiscroll/connect/resources/events.rb +19 -4
- data/lib/mobiscroll/connect/resources/webhooks.rb +70 -3
- data/lib/mobiscroll/connect/version.rb +1 -1
- data/lib/mobiscroll/connect/webhook_verification.rb +250 -0
- data/lib/mobiscroll/connect.rb +1 -0
- data/mobiscroll-connect.gemspec +1 -1
- metadata +4 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: ef1573ac2afaa4ddba1a958938b7811cf392ce7186ead74fa12c2639ed1c1f20
|
|
4
|
+
data.tar.gz: 0fe20784ecce947f01f403ee21c59faece8030089bfa0b456f316502babaa3bb
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 8709962bfbeea45cb19bdbb156296caf2904f9fb5d9440707b3fd00447df26b7b331ba15e0b722c38c4fe5106d6e06448d1cab6ced1be3523368694d4b4d7915
|
|
7
|
+
data.tar.gz: 5b8c9d1e44203df175ea3b61e05d625163ac4538eda4e68d0d0923824cfac94f368354c379fdfeeb1b93a34097741f0efafb99703747cd91b3bd7727455b6bc1
|
data/CHANGELOG.md
CHANGED
|
@@ -2,7 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to the Mobiscroll Connect Ruby SDK (RubyGems: `mobiscroll-connect`) are documented in this file.
|
|
4
4
|
|
|
5
|
-
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this SDK
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this SDK's major.minor always matches the Connect API's (for example API 1.5.x → SDK 1.5.x): each release bumps only the patch, including releases with breaking changes. Patch numbers are independent per SDK, so this file covers the Ruby SDK only.
|
|
6
|
+
|
|
7
|
+
## [1.6.1] — 2026-11-11
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- We added the missing `auth.revoke(token = nil)` for `POST /api/oauth/revoke`: it revokes the user's Connect access and refresh tokens.
|
|
12
|
+
- We fixed `generate_auth_url` not accepting `theme:`. It now accepts `'light'`, `'dark'` or `'auto'`, which sets the color scheme of the Connect pages.
|
|
13
|
+
- We added the missing `account` (the connected account the calendar belongs to) and `read_only` (`true` when the connection cannot write to it) to `Calendar` objects.
|
|
14
|
+
- We fixed `events.create` and `events.update` leaving out `status` and `conference_data:`. They now send `status`, and `conference_data:` as `conferenceData` (for example `{ 'autoGenerate' => true }`).
|
|
15
|
+
- We fixed `events.create` and `events.update` silently leaving out `conferenceData:`, `allDay:`, `recurringEventId:` and `updateMode:`, the API's spelling of `conference_data:`, `all_day:`, `recurring_event_id:` and `update_mode:`. They now accept both spellings.
|
|
16
|
+
- `events.create` and `events.update` now send `attendees` as email strings, as the API expects; an `Attendee` or a Hash is reduced to its email.
|
|
17
|
+
- `events.create` and `events.update` no longer send `color`, which the API does not accept on writes.
|
|
18
|
+
|
|
19
|
+
## [1.6.0] — 2026-10-08
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- `webhooks.verify_webhook` checks a delivery's Ed25519 signature and timestamp and returns the parsed `WebhookDelivery`, or raises `WebhookVerificationError`. It fetches and caches the public keys from `/.well-known/webhook-keys` and re-fetches them once before rejecting, so key rotations need no action.
|
|
24
|
+
- `webhook_public_key` client option: a pinned key, used only when the keys endpoint cannot be reached.
|
|
25
|
+
- `Mobiscroll::Connect.verify_webhook_signature` for verifying against keys you supply, with no fetching.
|
|
6
26
|
|
|
7
27
|
## [1.5.1] — 2026-09-22
|
|
8
28
|
|
data/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Ruby client for [Mobiscroll Connect](https://mobiscroll.com/connect), the calend
|
|
|
4
4
|
|
|
5
5
|
[](https://rubygems.org/gems/mobiscroll-connect)
|
|
6
6
|
|
|
7
|
-
**[RubyGems](https://rubygems.org/gems/mobiscroll-connect)** · **[Documentation](https://mobiscroll.com/docs/connect/ruby-sdk)** · **[Changelog](CHANGELOG.md)** · **[Source](https://github.com/acidb/mobiscroll-connect-sdks/tree/main/sdks/ruby)**
|
|
7
|
+
**[RubyGems](https://rubygems.org/gems/mobiscroll-connect)** · **[Documentation](https://mobiscroll.com/docs/connect/ruby-sdk)** · **[Changelog](https://github.com/acidb/mobiscroll-connect-sdks/blob/main/sdks/ruby/CHANGELOG.md)** · **[Source](https://github.com/acidb/mobiscroll-connect-sdks/tree/main/sdks/ruby)**
|
|
8
8
|
|
|
9
9
|
## Installation
|
|
10
10
|
|
|
@@ -40,6 +40,7 @@ client = Mobiscroll::Connect::Client.new(
|
|
|
40
40
|
url = client.auth.generate_auth_url(
|
|
41
41
|
user_id: 'user-123',
|
|
42
42
|
lng: 'es', # optional: Connect page language, see https://mobiscroll.com/docs/connect/localization#supported-languages
|
|
43
|
+
theme: 'dark', # optional: Connect page color scheme, 'light' | 'dark' | 'auto'
|
|
43
44
|
providers: [
|
|
44
45
|
Mobiscroll::Connect::Provider::GOOGLE,
|
|
45
46
|
Mobiscroll::Connect::Provider::MICROSOFT
|
|
@@ -84,10 +85,24 @@ end
|
|
|
84
85
|
|
|
85
86
|
### 5. Disconnect a provider
|
|
86
87
|
|
|
88
|
+
Disconnect one account (its `id` from `get_connection_status`), or every account of a provider. This stops the account's webhook subscriptions and deletes its provider credentials; it does not revoke the user's Connect tokens.
|
|
89
|
+
|
|
87
90
|
```ruby
|
|
88
|
-
client.auth.disconnect(provider: Mobiscroll::Connect::Provider::GOOGLE)
|
|
91
|
+
client.auth.disconnect(provider: Mobiscroll::Connect::Provider::GOOGLE, account: 'user@gmail.com')
|
|
92
|
+
client.auth.disconnect(provider: Mobiscroll::Connect::Provider::MICROSOFT)
|
|
89
93
|
```
|
|
90
94
|
|
|
95
|
+
### 6. Revoke tokens
|
|
96
|
+
|
|
97
|
+
`revoke` revokes the whole grant: every Connect access and refresh token of the user. It does not disconnect calendar accounts or stop webhooks, so to remove a user entirely, disconnect each provider first (that needs a valid access token), then revoke.
|
|
98
|
+
|
|
99
|
+
```ruby
|
|
100
|
+
client.auth.revoke # stored refresh token, else access token; clears the stored credentials
|
|
101
|
+
client.auth.revoke(stored_refresh_token) # a token you pass; stored credentials are kept
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
It returns a `RevokeResponse` with `success: true` for any token, including an unknown or already revoked one. With no argument and no stored credentials it raises `ValidationError` without making a request.
|
|
105
|
+
|
|
91
106
|
## Token refresh
|
|
92
107
|
|
|
93
108
|
The SDK automatically refreshes expired access tokens. When a request returns 401 and a `refresh_token` is available, the SDK:
|
|
@@ -98,6 +113,8 @@ The SDK automatically refreshes expired access tokens. When a request returns 40
|
|
|
98
113
|
|
|
99
114
|
Concurrent 401s share a single in-flight refresh — only one `POST /oauth/token` is ever issued per `Client` instance at a time.
|
|
100
115
|
|
|
116
|
+
**Running more than one instance.** The single in-flight refresh above is per `Client` instance. The SDK does not coordinate across processes — separate containers, cluster workers or serverless invocations each refresh from the tokens they hold in memory. Connect accepts concurrent refreshes of the same token, but refreshing with a copy that is two or more refreshes out of date revokes the user's authorization. Persist refreshed tokens to storage every instance reads, and call `client.set_credentials(...)` with the current tokens when a process starts a job or handles a request. See [Refreshing from several instances](https://mobiscroll.com/docs/connect/api/oauth#concurrent-refresh).
|
|
117
|
+
|
|
101
118
|
To persist refreshed tokens (e.g., back to a session or database):
|
|
102
119
|
|
|
103
120
|
```ruby
|
|
@@ -178,10 +195,12 @@ client.events.delete(
|
|
|
178
195
|
|
|
179
196
|
### Subscribe to calendar change notifications
|
|
180
197
|
|
|
198
|
+
Pass the calendar's real ID from `calendars.list`; an alias such as `primary` creates a duplicate subscription. A `channel_id` you supply that another user already holds is rejected with `Mobiscroll::Connect::Error` (HTTP 409).
|
|
199
|
+
|
|
181
200
|
```ruby
|
|
182
201
|
result = client.webhooks.subscribe_webhook(
|
|
183
202
|
provider: Mobiscroll::Connect::Provider::GOOGLE,
|
|
184
|
-
calendar_id: '
|
|
203
|
+
calendar_id: 'work@company.com'
|
|
185
204
|
)
|
|
186
205
|
puts result.channel_id
|
|
187
206
|
puts result.server_webhook_url
|
|
@@ -189,6 +208,8 @@ puts result.server_webhook_url
|
|
|
189
208
|
|
|
190
209
|
### Unsubscribe
|
|
191
210
|
|
|
211
|
+
Connect replaces the channel ID when it renews a subscription, so use the current one from the latest delivery's `metadata.channel_id`.
|
|
212
|
+
|
|
192
213
|
```ruby
|
|
193
214
|
client.webhooks.unsubscribe_webhook(
|
|
194
215
|
provider: 'google',
|
|
@@ -197,6 +218,42 @@ client.webhooks.unsubscribe_webhook(
|
|
|
197
218
|
)
|
|
198
219
|
```
|
|
199
220
|
|
|
221
|
+
### Verify webhook deliveries
|
|
222
|
+
|
|
223
|
+
Every delivery to your webhook URL is signed. `verify_webhook` checks the signature and the timestamp, then returns the parsed `WebhookDelivery`, or raises `WebhookVerificationError`. Pass the **raw** request body: a JSON body parser that runs first changes the bytes and every check fails.
|
|
224
|
+
|
|
225
|
+
```ruby
|
|
226
|
+
post '/webhooks/mobiscroll' do
|
|
227
|
+
begin
|
|
228
|
+
delivery = client.webhooks.verify_webhook(request.body.read, request.env)
|
|
229
|
+
rescue Mobiscroll::Connect::WebhookVerificationError => e
|
|
230
|
+
# 503 lets Connect retry when the keys could not be loaded; 401 is final.
|
|
231
|
+
halt(e.reason == 'no_public_keys' ? 503 : 401)
|
|
232
|
+
end
|
|
233
|
+
handle_delivery(delivery)
|
|
234
|
+
status 204
|
|
235
|
+
end
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Each event's `conference` is exactly what the delivery carried, not the join-URL string `events.list` returns: a Hash with the keys `url`, `provider`, `meetingProvider` and `data` (as sent, camelCase), or nil when absent. `conference_data` is the delivery's `conferenceData` (Connect 1.6.1 and later), the same object `events.list` returns, passed through unchanged.
|
|
239
|
+
|
|
240
|
+
`headers` can be a Hash with any key casing, a Rack env (`HTTP_WEBHOOK_ID` keys), or Rails' `request.headers` (pass `request.raw_post` as the body in Rails).
|
|
241
|
+
|
|
242
|
+
The public keys are fetched from `https://connect.mobiscroll.com/.well-known/webhook-keys` on the first delivery and cached for the whole process as the endpoint's `Cache-Control` allows. If no signature matches, the keys are fetched again (at most once a minute) before the delivery is rejected, so key rotations need no action on your side.
|
|
243
|
+
|
|
244
|
+
If your handler cannot make outbound requests, pin the key. `webhook_public_key` is used only when the keys endpoint cannot be reached; it stops working when Mobiscroll retires that key, so you must replace it on every rotation.
|
|
245
|
+
|
|
246
|
+
```ruby
|
|
247
|
+
client = Mobiscroll::Connect::Client.new(
|
|
248
|
+
client_id: ENV['MOBISCROLL_CLIENT_ID'],
|
|
249
|
+
client_secret: ENV['MOBISCROLL_CLIENT_SECRET'],
|
|
250
|
+
redirect_uri: ENV['MOBISCROLL_REDIRECT_URI'],
|
|
251
|
+
webhook_public_key: ENV['MOBISCROLL_WEBHOOK_PUBLIC_KEY'] # whpk_...
|
|
252
|
+
)
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
To check against keys you supply, with no fetching, call `Mobiscroll::Connect.verify_webhook_signature(raw_body, headers, ['whpk_...'])`. It raises `WebhookVerificationError` and returns `nil`. See [Verifying deliveries](https://mobiscroll.com/docs/connect/api/webhooks#verifying-deliveries).
|
|
256
|
+
|
|
200
257
|
## Error handling
|
|
201
258
|
|
|
202
259
|
All errors are subclasses of `Mobiscroll::Connect::Error`:
|
|
@@ -229,6 +286,7 @@ end
|
|
|
229
286
|
| `RateLimitError` | 429 | `retry_after` (seconds) |
|
|
230
287
|
| `ServerError` | 5xx | `status_code` |
|
|
231
288
|
| `NetworkError` | transport | `cause` |
|
|
289
|
+
| `WebhookVerificationError` | — (from `verify_webhook`) | `reason` |
|
|
232
290
|
|
|
233
291
|
## Minimal demo app
|
|
234
292
|
|
|
@@ -40,6 +40,10 @@ module Mobiscroll
|
|
|
40
40
|
@monitor.synchronize { @credentials }
|
|
41
41
|
end
|
|
42
42
|
|
|
43
|
+
def clear_credentials
|
|
44
|
+
@monitor.synchronize { @credentials = nil }
|
|
45
|
+
end
|
|
46
|
+
|
|
43
47
|
def on_tokens_refreshed(&block)
|
|
44
48
|
@on_tokens_refreshed = block
|
|
45
49
|
end
|
|
@@ -48,8 +52,9 @@ module Mobiscroll
|
|
|
48
52
|
execute(:get, path, query: query, body: nil, headers: headers)
|
|
49
53
|
end
|
|
50
54
|
|
|
51
|
-
|
|
52
|
-
|
|
55
|
+
# `skip_refresh: true` surfaces a 401 as-is instead of refreshing and retrying.
|
|
56
|
+
def post(path, body: nil, query: nil, headers: nil, skip_refresh: false)
|
|
57
|
+
execute(:post, path, query: query, body: body, headers: headers, retried: skip_refresh)
|
|
53
58
|
end
|
|
54
59
|
|
|
55
60
|
def put(path, body: nil, query: nil, headers: nil)
|
|
@@ -7,14 +7,15 @@ module Mobiscroll
|
|
|
7
7
|
|
|
8
8
|
def initialize(client_id:, client_secret:, redirect_uri:,
|
|
9
9
|
base_url: DEFAULT_BASE_URL, timeout: DEFAULT_TIMEOUT,
|
|
10
|
-
on_tokens_refreshed: nil)
|
|
10
|
+
on_tokens_refreshed: nil, webhook_public_key: nil)
|
|
11
11
|
@config = Config.new(
|
|
12
12
|
client_id: client_id,
|
|
13
13
|
client_secret: client_secret,
|
|
14
14
|
redirect_uri: redirect_uri,
|
|
15
15
|
base_url: base_url,
|
|
16
16
|
timeout: timeout,
|
|
17
|
-
on_tokens_refreshed: on_tokens_refreshed
|
|
17
|
+
on_tokens_refreshed: on_tokens_refreshed,
|
|
18
|
+
webhook_public_key: webhook_public_key
|
|
18
19
|
)
|
|
19
20
|
@api_client = ApiClient.new(@config)
|
|
20
21
|
@auth = Resources::Auth.new(@config, @api_client)
|
|
@@ -6,12 +6,14 @@ module Mobiscroll
|
|
|
6
6
|
DEFAULT_TIMEOUT = 30
|
|
7
7
|
|
|
8
8
|
class Config
|
|
9
|
-
|
|
9
|
+
# `webhook_public_key` is a pinned `whpk_` key, used by Webhooks#verify_webhook only when
|
|
10
|
+
# the keys endpoint cannot be reached; it stops verifying once Mobiscroll retires that key.
|
|
11
|
+
attr_reader :client_id, :client_secret, :redirect_uri, :base_url, :timeout, :webhook_public_key
|
|
10
12
|
attr_accessor :on_tokens_refreshed
|
|
11
13
|
|
|
12
14
|
def initialize(client_id:, client_secret:, redirect_uri:,
|
|
13
15
|
base_url: DEFAULT_BASE_URL, timeout: DEFAULT_TIMEOUT,
|
|
14
|
-
on_tokens_refreshed: nil)
|
|
16
|
+
on_tokens_refreshed: nil, webhook_public_key: nil)
|
|
15
17
|
raise Error, 'client_id is required' if client_id.nil? || client_id.empty?
|
|
16
18
|
raise Error, 'client_secret is required' if client_secret.nil? || client_secret.empty?
|
|
17
19
|
raise Error, 'redirect_uri is required' if redirect_uri.nil? || redirect_uri.empty?
|
|
@@ -22,6 +24,7 @@ module Mobiscroll
|
|
|
22
24
|
@base_url = base_url
|
|
23
25
|
@timeout = timeout
|
|
24
26
|
@on_tokens_refreshed = on_tokens_refreshed
|
|
27
|
+
@webhook_public_key = webhook_public_key
|
|
25
28
|
end
|
|
26
29
|
end
|
|
27
30
|
end
|
|
@@ -78,6 +78,21 @@ module Mobiscroll
|
|
|
78
78
|
end
|
|
79
79
|
end
|
|
80
80
|
|
|
81
|
+
# Raised when a webhook delivery fails verification. Do not process it. Respond with 503
|
|
82
|
+
# when +reason+ is 'no_public_keys' (the keys could not be fetched, so Connect retries) and
|
|
83
|
+
# with 401 otherwise.
|
|
84
|
+
#
|
|
85
|
+
# +reason+ is one of 'missing_headers', 'invalid_timestamp', 'timestamp_out_of_tolerance',
|
|
86
|
+
# 'no_public_keys', 'no_matching_signature' or 'invalid_payload'.
|
|
87
|
+
class WebhookVerificationError < Error
|
|
88
|
+
attr_reader :reason
|
|
89
|
+
|
|
90
|
+
def initialize(message = 'Webhook verification failed', reason: nil)
|
|
91
|
+
super(message, code: 'WEBHOOK_VERIFICATION_ERROR')
|
|
92
|
+
@reason = reason
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
|
|
81
96
|
# Maps an HTTP response (status + body hash + headers) to the matching
|
|
82
97
|
# typed error. Returns nil for 2xx responses.
|
|
83
98
|
def self.map_response_error(status, body, headers)
|
|
@@ -104,8 +104,18 @@ module Mobiscroll
|
|
|
104
104
|
end
|
|
105
105
|
end
|
|
106
106
|
|
|
107
|
-
|
|
108
|
-
|
|
107
|
+
RevokeResponse = Struct.new(:success, keyword_init: true) do
|
|
108
|
+
def self.from_h(hash)
|
|
109
|
+
return nil if hash.nil?
|
|
110
|
+
|
|
111
|
+
new(success: hash['success'] || hash[:success])
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# A calendar exposed by one of the supported providers. `account` is the connected account
|
|
116
|
+
# it belongs to; `read_only` is true when the authenticated connection cannot write to it.
|
|
117
|
+
Calendar = Struct.new(:provider, :id, :title, :time_zone, :color, :description, :original,
|
|
118
|
+
:account, :read_only, keyword_init: true) do
|
|
109
119
|
def self.from_h(hash)
|
|
110
120
|
return nil if hash.nil?
|
|
111
121
|
|
|
@@ -116,7 +126,9 @@ module Mobiscroll
|
|
|
116
126
|
time_zone: hash['timeZone'] || hash[:timeZone] || hash['time_zone'],
|
|
117
127
|
color: hash['color'] || hash[:color],
|
|
118
128
|
description: hash['description'] || hash[:description],
|
|
119
|
-
original: hash['original'] || hash[:original]
|
|
129
|
+
original: hash['original'] || hash[:original],
|
|
130
|
+
account: hash['account'] || hash[:account],
|
|
131
|
+
read_only: (hash.key?('readOnly') ? hash['readOnly'] : hash[:readOnly]) == true
|
|
120
132
|
)
|
|
121
133
|
end
|
|
122
134
|
end
|
|
@@ -242,6 +254,55 @@ module Mobiscroll
|
|
|
242
254
|
end
|
|
243
255
|
end
|
|
244
256
|
|
|
257
|
+
# A changed event in a webhook delivery: every CalendarEvent field plus `change_type`
|
|
258
|
+
# ('created', 'updated' or 'deleted'). `conference` is the raw Hash as delivered (Events#list
|
|
259
|
+
# returns a join-URL String instead). Deleted placeholders lack `original` (and, in deliveries
|
|
260
|
+
# sent before Connect 1.6.1, `calendar_id`); rely only on `id`, `provider`, `calendar_id`,
|
|
261
|
+
# `change_type`.
|
|
262
|
+
WebhookEvent = Struct.new(*CalendarEvent.members, :change_type, keyword_init: true) do
|
|
263
|
+
def self.from_h(hash)
|
|
264
|
+
return nil if hash.nil?
|
|
265
|
+
|
|
266
|
+
new(**CalendarEvent.from_h(hash).to_h, change_type: hash['changeType'] || hash[:changeType])
|
|
267
|
+
end
|
|
268
|
+
end
|
|
269
|
+
|
|
270
|
+
# `metadata` of a webhook delivery.
|
|
271
|
+
WebhookDeliveryMetadata = Struct.new(:channel_id, :event_count, :is_initial_sync, keyword_init: true) do
|
|
272
|
+
def self.from_h(hash)
|
|
273
|
+
return nil if hash.nil?
|
|
274
|
+
|
|
275
|
+
key = 'isInitialSync'
|
|
276
|
+
new(
|
|
277
|
+
channel_id: hash['channelId'] || hash[:channelId],
|
|
278
|
+
event_count: hash['eventCount'] || hash[:eventCount],
|
|
279
|
+
is_initial_sync: hash.key?(key) ? hash[key] : hash[key.to_sym]
|
|
280
|
+
)
|
|
281
|
+
end
|
|
282
|
+
end
|
|
283
|
+
|
|
284
|
+
# A verified webhook delivery, returned by Webhooks#verify_webhook. `change_type` is
|
|
285
|
+
# 'created', 'updated', 'deleted' or 'mixed'; `timestamp` is the ISO 8601 time Connect
|
|
286
|
+
# processed the change.
|
|
287
|
+
WebhookDelivery = Struct.new(
|
|
288
|
+
:provider, :user_id, :calendar_id, :events, :change_type, :timestamp, :metadata, keyword_init: true
|
|
289
|
+
) do
|
|
290
|
+
def self.from_h(hash)
|
|
291
|
+
return nil if hash.nil?
|
|
292
|
+
|
|
293
|
+
metadata = hash['metadata'] || hash[:metadata]
|
|
294
|
+
new(
|
|
295
|
+
provider: hash['provider'] || hash[:provider],
|
|
296
|
+
user_id: hash['userId'] || hash[:userId],
|
|
297
|
+
calendar_id: hash['calendarId'] || hash[:calendarId],
|
|
298
|
+
events: Array(hash['events'] || hash[:events]).filter_map { |e| WebhookEvent.from_h(e) if e.is_a?(Hash) },
|
|
299
|
+
change_type: hash['changeType'] || hash[:changeType],
|
|
300
|
+
timestamp: hash['timestamp'] || hash[:timestamp],
|
|
301
|
+
metadata: metadata.is_a?(Hash) ? WebhookDeliveryMetadata.from_h(metadata) : nil
|
|
302
|
+
)
|
|
303
|
+
end
|
|
304
|
+
end
|
|
305
|
+
|
|
245
306
|
# Response from Webhooks#unsubscribe_webhook. `success` is true whenever the local
|
|
246
307
|
# mapping was removed, even if the provider-side unsubscribe itself failed — `message`
|
|
247
308
|
# explains what happened in that case.
|
|
@@ -11,7 +11,10 @@ module Mobiscroll
|
|
|
11
11
|
@api_client = api_client
|
|
12
12
|
end
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
# Builds the consent URL to redirect the user to. `lng` is the Connect page language
|
|
15
|
+
# (e.g. 'es'); `theme` is the Connect page color scheme: 'light', 'dark' or 'auto'
|
|
16
|
+
# (follows the device setting), the project's default theme when nil.
|
|
17
|
+
def generate_auth_url(user_id:, scope: nil, state: nil, providers: nil, lng: nil, theme: nil)
|
|
15
18
|
params = {
|
|
16
19
|
'response_type' => 'code',
|
|
17
20
|
'client_id' => @config.client_id,
|
|
@@ -21,6 +24,7 @@ module Mobiscroll
|
|
|
21
24
|
params['scope'] = scope if scope
|
|
22
25
|
params['state'] = state if state
|
|
23
26
|
params['lng'] = lng if lng
|
|
27
|
+
params['theme'] = theme if theme
|
|
24
28
|
|
|
25
29
|
query = URI.encode_www_form(params)
|
|
26
30
|
|
|
@@ -57,6 +61,21 @@ module Mobiscroll
|
|
|
57
61
|
ConnectionStatus.from_h(parsed)
|
|
58
62
|
end
|
|
59
63
|
|
|
64
|
+
# Disconnects a calendar provider account.
|
|
65
|
+
#
|
|
66
|
+
# Removes the account (or, without +account+, every account of the provider)
|
|
67
|
+
# from the user: stops its webhook subscriptions and deletes the stored
|
|
68
|
+
# provider credentials. It does not revoke the user's Connect access or
|
|
69
|
+
# refresh tokens (see #revoke), nor the grant at Google or Microsoft.
|
|
70
|
+
#
|
|
71
|
+
# @param provider [String] a Provider constant
|
|
72
|
+
# @param account [String, nil] the +id+ of an account from #get_connection_status
|
|
73
|
+
# (<tt>connections[provider][].id</tt>)
|
|
74
|
+
# @return [DisconnectResponse]
|
|
75
|
+
#
|
|
76
|
+
# @example
|
|
77
|
+
# client.auth.disconnect(provider: Mobiscroll::Connect::Provider::GOOGLE, account: 'user@gmail.com')
|
|
78
|
+
# client.auth.disconnect(provider: Mobiscroll::Connect::Provider::MICROSOFT)
|
|
60
79
|
def disconnect(provider:, account: nil)
|
|
61
80
|
query = { 'provider' => provider }
|
|
62
81
|
query['account'] = account if account
|
|
@@ -68,6 +87,38 @@ module Mobiscroll
|
|
|
68
87
|
end
|
|
69
88
|
DisconnectResponse.from_h(parsed)
|
|
70
89
|
end
|
|
90
|
+
|
|
91
|
+
# Revokes the user's Connect access and refresh tokens.
|
|
92
|
+
#
|
|
93
|
+
# Revokes the whole grant: every access and refresh token issued for this
|
|
94
|
+
# user. It does not disconnect calendar accounts or stop webhook
|
|
95
|
+
# subscriptions. To remove a user entirely, call #disconnect for each
|
|
96
|
+
# provider first (it needs a valid access token), then #revoke.
|
|
97
|
+
#
|
|
98
|
+
# @param token [String, nil] access or refresh token to revoke. Defaults to
|
|
99
|
+
# the stored refresh token, else the stored access token; the stored
|
|
100
|
+
# credentials are then cleared.
|
|
101
|
+
# @return [RevokeResponse] success is true, also for an unknown or already
|
|
102
|
+
# revoked token
|
|
103
|
+
# @raise [ValidationError] when no token is given and none is stored
|
|
104
|
+
#
|
|
105
|
+
# @example
|
|
106
|
+
# client.auth.disconnect(provider: Mobiscroll::Connect::Provider::GOOGLE)
|
|
107
|
+
# client.auth.revoke
|
|
108
|
+
#
|
|
109
|
+
# # Or revoke a token you stored yourself
|
|
110
|
+
# client.auth.revoke(stored_refresh_token)
|
|
111
|
+
def revoke(token = nil)
|
|
112
|
+
stored = @api_client.credentials
|
|
113
|
+
revoke_token = token || [stored&.refresh_token, stored&.access_token].find { |t| t && !t.empty? }
|
|
114
|
+
if revoke_token.nil? || revoke_token.empty?
|
|
115
|
+
raise ValidationError, 'No token to revoke: pass one or set credentials first'
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
parsed = @api_client.post('/oauth/revoke', body: { 'token' => revoke_token }, skip_refresh: true)
|
|
119
|
+
@api_client.clear_credentials if token.nil?
|
|
120
|
+
RevokeResponse.from_h(parsed)
|
|
121
|
+
end
|
|
71
122
|
end
|
|
72
123
|
end
|
|
73
124
|
end
|
|
@@ -10,6 +10,12 @@ module Mobiscroll
|
|
|
10
10
|
@api_client = api_client
|
|
11
11
|
end
|
|
12
12
|
|
|
13
|
+
# The wire (camelCase) spelling of an optional field is accepted too, as the Python SDK does.
|
|
14
|
+
WIRE_KEYS = {
|
|
15
|
+
allDay: :all_day, recurringEventId: :recurring_event_id, updateMode: :update_mode,
|
|
16
|
+
conferenceData: :conference_data
|
|
17
|
+
}.freeze
|
|
18
|
+
|
|
13
19
|
def list(start: nil, end: nil, calendar_ids: nil, page_size: nil,
|
|
14
20
|
next_page_token: nil, single_events: nil)
|
|
15
21
|
end_time = binding.local_variable_get(:end)
|
|
@@ -68,6 +74,7 @@ module Mobiscroll
|
|
|
68
74
|
private
|
|
69
75
|
|
|
70
76
|
def build_event_body(params)
|
|
77
|
+
params = params.to_h { |key, value| [WIRE_KEYS.fetch(key.to_sym, key.to_sym), value] }
|
|
71
78
|
body = {}
|
|
72
79
|
body['provider'] = params[:provider] if params.key?(:provider)
|
|
73
80
|
body['calendarId'] = params[:calendar_id] if params.key?(:calendar_id)
|
|
@@ -77,26 +84,34 @@ module Mobiscroll
|
|
|
77
84
|
body['end'] = params[:end] if params.key?(:end)
|
|
78
85
|
body['allDay'] = params[:all_day] if params.key?(:all_day)
|
|
79
86
|
body['description'] = params[:description] if params.key?(:description)
|
|
80
|
-
body['color'] = params[:color] if params.key?(:color)
|
|
81
87
|
body['location'] = params[:location] if params.key?(:location)
|
|
82
88
|
body['recurringEventId'] = params[:recurring_event_id] if params.key?(:recurring_event_id)
|
|
83
89
|
body['updateMode'] = params[:update_mode] if params.key?(:update_mode)
|
|
84
90
|
body['availability'] = params[:availability] if params.key?(:availability)
|
|
85
91
|
body['privacy'] = params[:privacy] if params.key?(:privacy)
|
|
92
|
+
body['status'] = params[:status] if params.key?(:status)
|
|
86
93
|
|
|
87
94
|
if params.key?(:recurrence)
|
|
88
95
|
body['recurrence'] =
|
|
89
96
|
params[:recurrence].is_a?(RecurrenceRule) ? params[:recurrence].to_wire : params[:recurrence]
|
|
90
97
|
end
|
|
91
98
|
|
|
92
|
-
if params.key?(:attendees)
|
|
93
|
-
body['attendees'] = params[:attendees].map { |a| a.is_a?(Attendee) ? a.to_h : a }
|
|
94
|
-
end
|
|
99
|
+
body['attendees'] = Array(params[:attendees]).map { |a| attendee_email(a) } if params.key?(:attendees)
|
|
95
100
|
|
|
96
101
|
body['conference'] = params[:conference] if params.key?(:conference)
|
|
102
|
+
body['conferenceData'] = params[:conference_data] if params.key?(:conference_data)
|
|
97
103
|
body['custom'] = params[:custom] if params.key?(:custom)
|
|
98
104
|
body
|
|
99
105
|
end
|
|
106
|
+
|
|
107
|
+
# The API takes attendees as email strings; an Attendee or a Hash is reduced to its email.
|
|
108
|
+
def attendee_email(attendee)
|
|
109
|
+
case attendee
|
|
110
|
+
when Attendee then attendee.email
|
|
111
|
+
when Hash then attendee['email'] || attendee[:email]
|
|
112
|
+
else attendee
|
|
113
|
+
end
|
|
114
|
+
end
|
|
100
115
|
end
|
|
101
116
|
end
|
|
102
117
|
end
|
|
@@ -1,19 +1,26 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require 'json'
|
|
4
|
+
require 'uri'
|
|
4
5
|
|
|
5
6
|
module Mobiscroll
|
|
6
7
|
module Connect
|
|
7
8
|
module Resources
|
|
8
9
|
class Webhooks
|
|
9
|
-
|
|
10
|
+
RETRYABLE_REASONS = %w[no_matching_signature no_public_keys].freeze
|
|
11
|
+
|
|
12
|
+
def initialize(config, api_client)
|
|
13
|
+
@config = config
|
|
10
14
|
@api_client = api_client
|
|
11
15
|
end
|
|
12
16
|
|
|
13
17
|
# Subscribes to push notifications for changes on a calendar.
|
|
14
18
|
#
|
|
15
|
-
#
|
|
16
|
-
#
|
|
19
|
+
# Pass the calendar's real ID from Calendars#list as `calendar_id`; an alias such as
|
|
20
|
+
# 'primary' creates a duplicate subscription. `channel_id` is auto-generated
|
|
21
|
+
# server-side when omitted; one that another user already holds is rejected with
|
|
22
|
+
# Mobiscroll::Connect::Error (HTTP 409). `expiration` is a provider-specific timestamp
|
|
23
|
+
# (ms epoch) the caller can suggest.
|
|
17
24
|
def subscribe_webhook(provider:, calendar_id:, channel_id: nil, expiration: nil)
|
|
18
25
|
body = { 'provider' => provider, 'calendarId' => calendar_id }
|
|
19
26
|
body['channelId'] = channel_id if channel_id
|
|
@@ -29,6 +36,9 @@ module Mobiscroll
|
|
|
29
36
|
# The backend treats a 200 response as final even when the provider-side
|
|
30
37
|
# unsubscribe itself failed (e.g. an already-expired subscription) — the local
|
|
31
38
|
# mapping is removed either way, and `message` explains what happened.
|
|
39
|
+
#
|
|
40
|
+
# Use the current channel ID: Connect replaces it when it renews a subscription, so
|
|
41
|
+
# take it from the latest delivery's `metadata.channel_id`.
|
|
32
42
|
def unsubscribe_webhook(provider:, channel_id:, resource_id: nil)
|
|
33
43
|
body = { 'provider' => provider, 'channelId' => channel_id }
|
|
34
44
|
body['resourceId'] = resource_id if resource_id
|
|
@@ -36,6 +46,63 @@ module Mobiscroll
|
|
|
36
46
|
parsed = @api_client.post('/unsubscribe-webhook', body: JSON.generate(body))
|
|
37
47
|
UnsubscribeWebhookResponse.from_h(parsed)
|
|
38
48
|
end
|
|
49
|
+
|
|
50
|
+
# Verifies that a webhook delivery came from Mobiscroll Connect, and parses it.
|
|
51
|
+
#
|
|
52
|
+
# Fetches the public keys from `/.well-known/webhook-keys` on first use and caches them for
|
|
53
|
+
# the whole process, refreshing them as the endpoint's `Cache-Control` allows. When no
|
|
54
|
+
# signature matches, it re-fetches the keys once (at most once a minute) before rejecting,
|
|
55
|
+
# so a key rotation never rejects genuine deliveries. `webhook_public_key` from the config
|
|
56
|
+
# is used only when the endpoint cannot be reached.
|
|
57
|
+
#
|
|
58
|
+
# `payload` is the raw request body String, exactly as received; not a parsed Hash.
|
|
59
|
+
# `headers` is a Hash (any key casing) or a Rack env / Rails `request.headers`.
|
|
60
|
+
#
|
|
61
|
+
# Returns a WebhookDelivery. Raises WebhookVerificationError when the delivery is not
|
|
62
|
+
# verified: respond with 503 when its `reason` is 'no_public_keys' (Connect retries)
|
|
63
|
+
# and with 401 otherwise (Connect does not retry).
|
|
64
|
+
#
|
|
65
|
+
# post '/webhooks/mobiscroll' do
|
|
66
|
+
# delivery = client.webhooks.verify_webhook(request.body.read, request.env)
|
|
67
|
+
# handle_delivery(delivery)
|
|
68
|
+
# status 204
|
|
69
|
+
# rescue Mobiscroll::Connect::WebhookVerificationError => e
|
|
70
|
+
# halt(e.reason == 'no_public_keys' ? 503 : 401)
|
|
71
|
+
# end
|
|
72
|
+
def verify_webhook(payload, headers)
|
|
73
|
+
store = WebhookKeyStore.for_url(URI.join(@config.base_url, WEBHOOK_KEYS_PATH).to_s)
|
|
74
|
+
|
|
75
|
+
begin
|
|
76
|
+
Connect.verify_webhook_signature(payload, headers, keys_or_pinned(store.keys))
|
|
77
|
+
rescue WebhookVerificationError => e
|
|
78
|
+
raise unless RETRYABLE_REASONS.include?(e.reason) && store.can_refetch?
|
|
79
|
+
|
|
80
|
+
store.refresh
|
|
81
|
+
Connect.verify_webhook_signature(payload, headers, keys_or_pinned(store.keys))
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
parse_delivery(payload)
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
private
|
|
88
|
+
|
|
89
|
+
# The pinned key is never merged with fetched keys: after an emergency rotation a pinned
|
|
90
|
+
# retired key must stop verifying.
|
|
91
|
+
def keys_or_pinned(keys)
|
|
92
|
+
pinned = @config.webhook_public_key
|
|
93
|
+
keys.empty? && pinned && !pinned.empty? ? [pinned] : keys
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
def parse_delivery(payload)
|
|
97
|
+
parsed = begin
|
|
98
|
+
JSON.parse(payload.dup.force_encoding(Encoding::UTF_8))
|
|
99
|
+
rescue JSON::ParserError, EncodingError
|
|
100
|
+
nil
|
|
101
|
+
end
|
|
102
|
+
return WebhookDelivery.from_h(parsed) if parsed.is_a?(Hash)
|
|
103
|
+
|
|
104
|
+
raise WebhookVerificationError.new('Webhook payload is not a JSON object', reason: 'invalid_payload')
|
|
105
|
+
end
|
|
39
106
|
end
|
|
40
107
|
end
|
|
41
108
|
end
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'base64'
|
|
4
|
+
require 'faraday'
|
|
5
|
+
require 'json'
|
|
6
|
+
require 'openssl'
|
|
7
|
+
|
|
8
|
+
module Mobiscroll
|
|
9
|
+
module Connect
|
|
10
|
+
WEBHOOK_TOLERANCE_SECONDS = 300
|
|
11
|
+
WEBHOOK_KEYS_PATH = '/.well-known/webhook-keys'
|
|
12
|
+
|
|
13
|
+
# Verifies the Standard Webhooks `v1a` (Ed25519) signature of a Mobiscroll Connect delivery
|
|
14
|
+
# against the given public keys, without fetching anything.
|
|
15
|
+
#
|
|
16
|
+
# Use it with a pinned key in handlers that cannot make outbound requests. Otherwise prefer
|
|
17
|
+
# `client.webhooks.verify_webhook`, which fetches and refreshes the keys for you.
|
|
18
|
+
#
|
|
19
|
+
# `payload` is the raw request body String, exactly as received. `headers` is a Hash (any
|
|
20
|
+
# key casing, Array values take the first) or a Rack env / Rails `request.headers`, where
|
|
21
|
+
# `HTTP_WEBHOOK_ID`-style keys are matched too. `public_keys` are `whpk_` keys; the delivery
|
|
22
|
+
# is genuine if any signature verifies against any key. `now` is the current Unix time in
|
|
23
|
+
# seconds, defaulting to the system clock.
|
|
24
|
+
#
|
|
25
|
+
# Returns nil. Raises WebhookVerificationError when the delivery is not genuine or cannot
|
|
26
|
+
# be checked.
|
|
27
|
+
#
|
|
28
|
+
# Mobiscroll::Connect.verify_webhook_signature(
|
|
29
|
+
# request.body.read, request.env, [ENV.fetch('MOBISCROLL_WEBHOOK_PUBLIC_KEY')]
|
|
30
|
+
# )
|
|
31
|
+
def self.verify_webhook_signature(payload, headers, public_keys,
|
|
32
|
+
tolerance_seconds: WEBHOOK_TOLERANCE_SECONDS, now: nil)
|
|
33
|
+
WebhookSignature.verify(payload, headers, public_keys, tolerance_seconds: tolerance_seconds, now: now)
|
|
34
|
+
nil
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# @api private
|
|
38
|
+
module WebhookSignature
|
|
39
|
+
PUBLIC_KEY_PREFIX = 'whpk_'
|
|
40
|
+
SIGNATURE_VERSION = 'v1a'
|
|
41
|
+
# DER SubjectPublicKeyInfo header for an Ed25519 key; `OpenSSL::PKey.new_raw_public_key`
|
|
42
|
+
# needs openssl gem 3.2+, which Ruby 3.2 does not bundle.
|
|
43
|
+
ED25519_SPKI_PREFIX = ['302a300506032b6570032100'].pack('H*').freeze
|
|
44
|
+
|
|
45
|
+
module_function
|
|
46
|
+
|
|
47
|
+
def verify(payload, headers, public_keys, tolerance_seconds:, now:)
|
|
48
|
+
unless payload.is_a?(String)
|
|
49
|
+
raise WebhookVerificationError.new(
|
|
50
|
+
'Pass the raw request body as a String, not a parsed object', reason: 'invalid_payload'
|
|
51
|
+
)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
id = read_header(headers, 'webhook-id')
|
|
55
|
+
timestamp = read_header(headers, 'webhook-timestamp')
|
|
56
|
+
signature_header = read_header(headers, 'webhook-signature')
|
|
57
|
+
if [id, timestamp, signature_header].any? { |value| value.nil? || value.empty? }
|
|
58
|
+
raise WebhookVerificationError.new(
|
|
59
|
+
'Missing webhook-id, webhook-timestamp or webhook-signature header', reason: 'missing_headers'
|
|
60
|
+
)
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
check_timestamp(timestamp, tolerance_seconds, now || Time.now.to_i)
|
|
64
|
+
|
|
65
|
+
keys = Array(public_keys).filter_map { |key| parse_public_key(key) }
|
|
66
|
+
if keys.empty?
|
|
67
|
+
raise WebhookVerificationError.new('No valid webhook public keys available', reason: 'no_public_keys')
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
signed_content = "#{id}.#{timestamp}.".b << payload.b
|
|
71
|
+
return if signature_header.split(/ /).any? { |entry| entry_matches?(entry, signed_content, keys) }
|
|
72
|
+
|
|
73
|
+
raise WebhookVerificationError.new('No webhook signature matched', reason: 'no_matching_signature')
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def check_timestamp(timestamp, tolerance_seconds, now)
|
|
77
|
+
unless timestamp.match?(/\A\d+\z/)
|
|
78
|
+
raise WebhookVerificationError.new('Invalid webhook-timestamp header', reason: 'invalid_timestamp')
|
|
79
|
+
end
|
|
80
|
+
return if (now - timestamp.to_i).abs <= tolerance_seconds
|
|
81
|
+
|
|
82
|
+
raise WebhookVerificationError.new(
|
|
83
|
+
'Webhook timestamp is outside the allowed tolerance', reason: 'timestamp_out_of_tolerance'
|
|
84
|
+
)
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def read_header(headers, name)
|
|
88
|
+
return nil unless headers.respond_to?(:each)
|
|
89
|
+
|
|
90
|
+
rack_name = "HTTP_#{name.upcase.tr('-', '_')}"
|
|
91
|
+
headers.each do |key, value|
|
|
92
|
+
next unless key.to_s.casecmp?(name) || key.to_s.casecmp?(rack_name)
|
|
93
|
+
|
|
94
|
+
value = value.first if value.is_a?(Array)
|
|
95
|
+
return value&.to_s&.b
|
|
96
|
+
end
|
|
97
|
+
nil
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def parse_public_key(value)
|
|
101
|
+
return nil unless value.is_a?(String)
|
|
102
|
+
|
|
103
|
+
raw = Base64.decode64(value.strip.delete_prefix(PUBLIC_KEY_PREFIX))
|
|
104
|
+
return nil unless raw.bytesize == 32
|
|
105
|
+
|
|
106
|
+
OpenSSL::PKey.read(ED25519_SPKI_PREFIX + raw)
|
|
107
|
+
rescue OpenSSL::PKey::PKeyError
|
|
108
|
+
nil
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def entry_matches?(entry, signed_content, keys)
|
|
112
|
+
version, separator, encoded = entry.partition(',')
|
|
113
|
+
return false if separator.empty? || version != SIGNATURE_VERSION
|
|
114
|
+
|
|
115
|
+
signature = Base64.decode64(encoded)
|
|
116
|
+
return false unless signature.bytesize == 64
|
|
117
|
+
|
|
118
|
+
keys.any? do |key|
|
|
119
|
+
key.verify(nil, signature, signed_content)
|
|
120
|
+
rescue OpenSSL::PKey::PKeyError
|
|
121
|
+
false
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
private_constant :WebhookSignature
|
|
126
|
+
|
|
127
|
+
# Process-wide cache of the keys published at one keys URL, shared by every client instance.
|
|
128
|
+
# Follows the endpoint's `Cache-Control`, re-fetches at most once a minute, and keeps the last
|
|
129
|
+
# good keys when a fetch fails. Concurrent callers share one in-flight fetch.
|
|
130
|
+
#
|
|
131
|
+
# @api private
|
|
132
|
+
class WebhookKeyStore
|
|
133
|
+
DEFAULT_MAX_AGE = 60 * 60
|
|
134
|
+
MAX_MAX_AGE = 24 * 60 * 60
|
|
135
|
+
MIN_REFETCH_INTERVAL = 60
|
|
136
|
+
FETCH_TIMEOUT = 10
|
|
137
|
+
|
|
138
|
+
@stores = {}
|
|
139
|
+
@stores_lock = Mutex.new
|
|
140
|
+
|
|
141
|
+
class << self
|
|
142
|
+
def for_url(url)
|
|
143
|
+
@stores_lock.synchronize { @stores[url] ||= new(url) }
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
# Clears every cached key set; for tests.
|
|
147
|
+
def reset!
|
|
148
|
+
@stores_lock.synchronize { @stores.clear }
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def initialize(url)
|
|
153
|
+
@url = url
|
|
154
|
+
@keys = [].freeze
|
|
155
|
+
@fetched_at = nil
|
|
156
|
+
@last_attempt_at = nil
|
|
157
|
+
@max_age = DEFAULT_MAX_AGE
|
|
158
|
+
@in_flight = false
|
|
159
|
+
@lock = Mutex.new
|
|
160
|
+
@cond = ConditionVariable.new
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# The current keys, fetching them first when they are missing or stale and a fetch is allowed.
|
|
164
|
+
def keys
|
|
165
|
+
fetch_if { |now| stale?(now) && can_refetch_at?(now) }
|
|
166
|
+
@lock.synchronize { @keys }
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def can_refetch?
|
|
170
|
+
@lock.synchronize { can_refetch_at?(Time.now.to_f) }
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# Fetches the keys unless a fetch was attempted in the last minute; joins one in flight.
|
|
174
|
+
def refresh
|
|
175
|
+
fetch_if { |now| can_refetch_at?(now) }
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
private
|
|
179
|
+
|
|
180
|
+
def stale?(now)
|
|
181
|
+
@fetched_at.nil? || now - @fetched_at > @max_age
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
def can_refetch_at?(now)
|
|
185
|
+
@last_attempt_at.nil? || now - @last_attempt_at >= MIN_REFETCH_INTERVAL
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# Starts a fetch when the block allows it, or waits for the one already in flight; the
|
|
189
|
+
# decision and the in-flight flag are taken under one lock so callers never fetch twice.
|
|
190
|
+
def fetch_if
|
|
191
|
+
@lock.synchronize do
|
|
192
|
+
if @in_flight
|
|
193
|
+
@cond.wait(@lock) while @in_flight
|
|
194
|
+
return
|
|
195
|
+
end
|
|
196
|
+
now = Time.now.to_f
|
|
197
|
+
return unless yield(now)
|
|
198
|
+
|
|
199
|
+
@in_flight = true
|
|
200
|
+
@last_attempt_at = now
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
result = nil
|
|
204
|
+
begin
|
|
205
|
+
result = fetch_keys
|
|
206
|
+
ensure
|
|
207
|
+
@lock.synchronize do
|
|
208
|
+
if result
|
|
209
|
+
@keys, @max_age = result
|
|
210
|
+
@fetched_at = Time.now.to_f
|
|
211
|
+
end
|
|
212
|
+
@in_flight = false
|
|
213
|
+
@cond.broadcast
|
|
214
|
+
end
|
|
215
|
+
end
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
# Returns [keys, max_age], or nil when the fetch fails or yields no usable key. Uses a plain
|
|
219
|
+
# connection: the keys endpoint is public and must never go through the token-refresh path.
|
|
220
|
+
def fetch_keys
|
|
221
|
+
response = Faraday.new(request: { timeout: FETCH_TIMEOUT, open_timeout: FETCH_TIMEOUT }).get(@url) do |req|
|
|
222
|
+
req.headers['Accept'] = 'application/json'
|
|
223
|
+
end
|
|
224
|
+
return nil unless response.success?
|
|
225
|
+
|
|
226
|
+
parsed = JSON.parse(response.body.to_s)
|
|
227
|
+
keys = Array(parsed.is_a?(Hash) ? parsed['keys'] : nil).filter_map { |entry| usable_key(entry) }
|
|
228
|
+
keys.empty? ? nil : [keys.freeze, parse_max_age(response.headers['cache-control'])]
|
|
229
|
+
rescue StandardError
|
|
230
|
+
nil
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
def usable_key(entry)
|
|
234
|
+
return nil unless entry.is_a?(Hash)
|
|
235
|
+
|
|
236
|
+
key = entry['key']
|
|
237
|
+
alg = entry['alg'].to_s
|
|
238
|
+
return nil unless key.is_a?(String) && key.start_with?(WebhookSignature::PUBLIC_KEY_PREFIX)
|
|
239
|
+
return nil unless alg.empty? || alg.casecmp?('ed25519')
|
|
240
|
+
|
|
241
|
+
key
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
def parse_max_age(cache_control)
|
|
245
|
+
match = /max-age=(\d+)/i.match(cache_control.to_s)
|
|
246
|
+
match ? [match[1].to_i, MAX_MAX_AGE].min : DEFAULT_MAX_AGE
|
|
247
|
+
end
|
|
248
|
+
end
|
|
249
|
+
end
|
|
250
|
+
end
|
data/lib/mobiscroll/connect.rb
CHANGED
|
@@ -6,6 +6,7 @@ require_relative 'connect/provider'
|
|
|
6
6
|
require_relative 'connect/config'
|
|
7
7
|
require_relative 'connect/models'
|
|
8
8
|
require_relative 'connect/api_client'
|
|
9
|
+
require_relative 'connect/webhook_verification'
|
|
9
10
|
require_relative 'connect/resources/auth'
|
|
10
11
|
require_relative 'connect/resources/calendars'
|
|
11
12
|
require_relative 'connect/resources/events'
|
data/mobiscroll-connect.gemspec
CHANGED
|
@@ -22,7 +22,7 @@ Gem::Specification.new do |spec|
|
|
|
22
22
|
|
|
23
23
|
spec.metadata = {
|
|
24
24
|
'homepage_uri' => spec.homepage,
|
|
25
|
-
'source_code_uri' => 'https://github.com/acidb/mobiscroll-connect-sdks',
|
|
25
|
+
'source_code_uri' => 'https://github.com/acidb/mobiscroll-connect-sdks/tree/main/sdks/ruby',
|
|
26
26
|
'documentation_uri' => 'https://mobiscroll.com/docs/connect/ruby-sdk',
|
|
27
27
|
'bug_tracker_uri' => 'https://github.com/acidb/mobiscroll-connect-sdks/issues',
|
|
28
28
|
'changelog_uri' => 'https://github.com/acidb/mobiscroll-connect-sdks/blob/main/sdks/ruby/CHANGELOG.md',
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: mobiscroll-connect
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 1.
|
|
4
|
+
version: 1.6.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Mobiscroll
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: bin
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-
|
|
11
|
+
date: 2026-11-11 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: base64
|
|
@@ -106,13 +106,14 @@ files:
|
|
|
106
106
|
- lib/mobiscroll/connect/resources/events.rb
|
|
107
107
|
- lib/mobiscroll/connect/resources/webhooks.rb
|
|
108
108
|
- lib/mobiscroll/connect/version.rb
|
|
109
|
+
- lib/mobiscroll/connect/webhook_verification.rb
|
|
109
110
|
- mobiscroll-connect.gemspec
|
|
110
111
|
homepage: https://mobiscroll.com/connect
|
|
111
112
|
licenses:
|
|
112
113
|
- MIT
|
|
113
114
|
metadata:
|
|
114
115
|
homepage_uri: https://mobiscroll.com/connect
|
|
115
|
-
source_code_uri: https://github.com/acidb/mobiscroll-connect-sdks
|
|
116
|
+
source_code_uri: https://github.com/acidb/mobiscroll-connect-sdks/tree/main/sdks/ruby
|
|
116
117
|
documentation_uri: https://mobiscroll.com/docs/connect/ruby-sdk
|
|
117
118
|
bug_tracker_uri: https://github.com/acidb/mobiscroll-connect-sdks/issues
|
|
118
119
|
changelog_uri: https://github.com/acidb/mobiscroll-connect-sdks/blob/main/sdks/ruby/CHANGELOG.md
|