studio-engine 0.137.0 → 0.139.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 +4 -4
- data/CHANGELOG.md +38 -0
- data/README.md +86 -1
- data/app/assets/tailwind/studio_engine/engine.css +235 -0
- data/app/controllers/concerns/studio/connection_flow.rb +1 -1
- data/app/controllers/sessions_controller.rb +12 -3
- data/app/controllers/studio/integrations_controller.rb +43 -0
- data/app/controllers/studio/local_reviews_controller.rb +12 -0
- data/app/javascript/studio/carousel.js +109 -0
- data/app/javascript/studio/controllers/carousel_captions_controller.js +42 -0
- data/app/javascript/studio/controllers/carousel_controller.js +243 -1
- data/app/javascript/studio/stimulus.js +3 -1
- data/app/models/concerns/studio/account.rb +143 -0
- data/app/models/concerns/studio/omniauth_user.rb +9 -17
- data/app/models/error_log.rb +14 -5
- data/app/views/studio/_carousel.html.erb +74 -14
- data/app/views/studio/integrations/_card.html.erb +50 -0
- data/app/views/studio/integrations/index.html.erb +22 -0
- data/app/views/studio/integrations/show.html.erb +24 -0
- data/app/views/style/_tricks.html.erb +38 -0
- data/config/studio_tricks.yml +7 -0
- data/db/migrate/20261006120001_ensure_error_logs_table.rb +3 -1
- data/db/migrate/20261006120002_ensure_theme_settings_table.rb +3 -2
- data/db/migrate/20261108160000_require_slugs_on_engine_tables.rb +119 -0
- data/db/migrate/20261108160001_add_engine_state_checks.rb +94 -0
- data/db/migrate/20261108170000_add_users_role_known_check.rb +69 -0
- data/lib/generators/studio/connections/connections_generator.rb +10 -0
- data/lib/studio/connections.rb +53 -12
- data/lib/studio/integrations/egnyte.rb +69 -0
- data/lib/studio/integrations/microsoft_365.rb +63 -0
- data/lib/studio/integrations/quickbooks.rb +86 -0
- data/lib/studio/integrations.rb +265 -0
- data/lib/studio/node_tooling/README.md +9 -1
- data/lib/studio/node_tooling/e2e_helpers.js +93 -1
- data/lib/studio/node_tooling/playwright_base.js +51 -4
- data/lib/studio/roles.rb +17 -0
- data/lib/studio/version.rb +1 -1
- data/lib/studio.rb +59 -1
- metadata +16 -2
|
@@ -53,6 +53,9 @@ module Studio
|
|
|
53
53
|
bin/rails db:migrate
|
|
54
54
|
Declare each provider in #{INITIALIZER}, then draw its routes in config/routes.rb:
|
|
55
55
|
Studio.draw_connection_routes(self, :files, path: "admin/files", controller: "admin/files")
|
|
56
|
+
Or enable an integration the engine defines (docs/INTEGRATIONS.md) and mount its page:
|
|
57
|
+
Studio.enable_integration :quickbooks, env: { client_id: "INTUIT_CLIENT_ID", client_secret: "INTUIT_CLIENT_SECRET" }
|
|
58
|
+
Studio.draw_integrations_routes(self)
|
|
56
59
|
Set the provider's client id and secret, and the app's Active Record encryption keys.
|
|
57
60
|
TEXT
|
|
58
61
|
end
|
|
@@ -68,6 +71,13 @@ module Studio
|
|
|
68
71
|
INITIALIZER_BODY = <<~RUBY
|
|
69
72
|
# frozen_string_literal: true
|
|
70
73
|
|
|
74
|
+
# Integrations the engine already defines (studio-engine docs/INTEGRATIONS.md):
|
|
75
|
+
# QuickBooks, Egnyte, Microsoft 365. One line each, naming this app's env
|
|
76
|
+
# vars; mount the page with Studio.draw_integrations_routes(self).
|
|
77
|
+
#
|
|
78
|
+
# Studio.enable_integration :quickbooks,
|
|
79
|
+
# env: { client_id: "INTUIT_CLIENT_ID", client_secret: "INTUIT_CLIENT_SECRET", environment: "INTUIT_ENVIRONMENT" }
|
|
80
|
+
#
|
|
71
81
|
# Connections (studio-engine docs/CONNECTIONS.md). One Studio.define_connection
|
|
72
82
|
# per provider this app connects; each stays off until its client id and
|
|
73
83
|
# secret are set. Draw its routes in config/routes.rb with
|
data/lib/studio/connections.rb
CHANGED
|
@@ -9,7 +9,7 @@ require "set"
|
|
|
9
9
|
|
|
10
10
|
module Studio
|
|
11
11
|
# CONNECTIONS: the generic tooling a host app uses to connect a third-party
|
|
12
|
-
# account over OAuth 2.0 (docs/CONNECTIONS.md). The
|
|
12
|
+
# account over OAuth 2.0 (docs/CONNECTIONS.md). The tooling knows no provider.
|
|
13
13
|
# A host declares each one in an initializer, and the engine gives it:
|
|
14
14
|
#
|
|
15
15
|
# * Studio::Connection, one table (studio_connections) holding one row per
|
|
@@ -30,7 +30,8 @@ module Studio
|
|
|
30
30
|
# account: :connect, account_param: "domain", account_format: /\A[a-z0-9-]{1,63}\z/
|
|
31
31
|
#
|
|
32
32
|
# Provider specifics (endpoints, scopes, quirks, readers, the admin page's
|
|
33
|
-
# live read) belong to the host. Nothing
|
|
33
|
+
# live read) belong to the host. Nothing in this file is named after a vendor:
|
|
34
|
+
# the engine's own definitions live in Studio::Integrations (docs/INTEGRATIONS.md).
|
|
34
35
|
module Connections
|
|
35
36
|
# What reaching a provider can raise below HTTP: TLS, refused, timed out, DNS.
|
|
36
37
|
NETWORK_ERRORS = [OpenSSL::SSL::SSLError, SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout].freeze
|
|
@@ -38,7 +39,18 @@ module Studio
|
|
|
38
39
|
ENCRYPTION_ENV = %w[ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY
|
|
39
40
|
ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT].freeze
|
|
40
41
|
|
|
41
|
-
|
|
42
|
+
# Every refusal below. A provider that names a trace_header (Intuit's
|
|
43
|
+
# intuit_tid) puts the answering call's trace id on the error: as #trace_id,
|
|
44
|
+
# and in the message, so the error log and the page carry it. Never a token.
|
|
45
|
+
class Error < StandardError
|
|
46
|
+
attr_reader :trace_header, :trace_id
|
|
47
|
+
|
|
48
|
+
def initialize(message = nil, trace_header: nil, trace_id: nil)
|
|
49
|
+
@trace_header = trace_header
|
|
50
|
+
@trace_id = trace_id.to_s.strip.presence
|
|
51
|
+
super(@trace_id && message ? "#{message} [#{@trace_header}: #{@trace_id}]" : message)
|
|
52
|
+
end
|
|
53
|
+
end
|
|
42
54
|
# The provider's client id or secret is not set on this server.
|
|
43
55
|
class NotConfigured < Error; end
|
|
44
56
|
# The provider no longer honours the stored grant: revoked, expired, superseded.
|
|
@@ -175,7 +187,7 @@ module Studio
|
|
|
175
187
|
:revoke_format, :account_source, :account_param, :account_format, :private_account,
|
|
176
188
|
:authorize_params, :exchange_params, :rotation, :refresh_expires_in_key, :declined_errors,
|
|
177
189
|
:refusal_hint, :revoked_errors, :revoked_pattern, :rate_limited_statuses, :filter_keys,
|
|
178
|
-
:revoke_note, :callback_check, :describe
|
|
190
|
+
:revoke_note, :callback_check, :describe, :trace_header
|
|
179
191
|
|
|
180
192
|
# Stand-in for the provider's token and revoke endpoints:
|
|
181
193
|
# (url, form, headers) -> [status, body]. nil means the provider itself.
|
|
@@ -195,7 +207,7 @@ module Studio
|
|
|
195
207
|
rotation: nil, refresh_expires_in_key: nil, declined_errors: %w[access_denied],
|
|
196
208
|
refusal_hint: "Check the app's redirect URI, then start again.", revoked_errors: %w[invalid_grant],
|
|
197
209
|
revoked_pattern: nil, rate_limited_statuses: [429], filter_keys: [], revoke_note: nil,
|
|
198
|
-
callback_check: nil, describe: nil)
|
|
210
|
+
callback_check: nil, describe: nil, trace_header: nil)
|
|
199
211
|
@key = key.to_s
|
|
200
212
|
raise ArgumentError, "a connection key is lower-case letters, digits and underscores: #{@key.inspect}" unless @key.match?(/\A[a-z][a-z0-9_]*\z/)
|
|
201
213
|
|
|
@@ -240,6 +252,10 @@ module Studio
|
|
|
240
252
|
@revoke_note = revoke_note || "Remove this app's access in #{@label} to revoke it there."
|
|
241
253
|
@callback_check = callback_check
|
|
242
254
|
@describe = describe
|
|
255
|
+
# A response header naming the call for the provider's support (Intuit:
|
|
256
|
+
# intuit_tid). Read from every token, refresh and revoke answer, logged
|
|
257
|
+
# with the call, kept as #last_trace_id and put on every error raised.
|
|
258
|
+
@trace_header = trace_header&.to_s
|
|
243
259
|
@cache = {}
|
|
244
260
|
@cache_lock = Mutex.new
|
|
245
261
|
end
|
|
@@ -349,6 +365,27 @@ module Studio
|
|
|
349
365
|
@cache_lock.synchronize { account ? @cache.delete(account.to_s.downcase) : @cache.clear }
|
|
350
366
|
end
|
|
351
367
|
|
|
368
|
+
# The trace_header value of this thread's latest call to the provider, or nil.
|
|
369
|
+
def last_trace_id = (Thread.current[:studio_connection_traces] ||= {})[key]
|
|
370
|
+
|
|
371
|
+
# Reads trace_header from a response's headers (a Hash or a Net::HTTPResponse),
|
|
372
|
+
# remembers it as last_trace_id, and logs it with the call (no token, no body).
|
|
373
|
+
# Host readers call it on their own responses too.
|
|
374
|
+
def record_trace(headers, call:, status:)
|
|
375
|
+
return nil unless trace_header
|
|
376
|
+
|
|
377
|
+
value = case headers
|
|
378
|
+
when Hash then headers.find { |name, _| name.to_s.casecmp?(trace_header) }&.last
|
|
379
|
+
else headers.respond_to?(:[]) ? headers[trace_header] : nil
|
|
380
|
+
end
|
|
381
|
+
value = Array(value).first.to_s.strip.presence
|
|
382
|
+
(Thread.current[:studio_connection_traces] ||= {})[key] = value
|
|
383
|
+
if defined?(::Rails) && ::Rails.respond_to?(:logger) && ::Rails.logger
|
|
384
|
+
::Rails.logger.info("[studio_connection] provider=#{key} call=#{call} status=#{status} #{trace_header}=#{value || '-'}")
|
|
385
|
+
end
|
|
386
|
+
value
|
|
387
|
+
end
|
|
388
|
+
|
|
352
389
|
# How many accounts have a token cached in this process (:memory).
|
|
353
390
|
def cached_count = @cache_lock.synchronize { @cache.size }
|
|
354
391
|
|
|
@@ -433,22 +470,24 @@ module Studio
|
|
|
433
470
|
when :secret_only then form = form.merge(client_secret:)
|
|
434
471
|
when :basic then headers["Authorization"] = "Basic #{Base64.strict_encode64("#{client_id}:#{client_secret}")}"
|
|
435
472
|
end
|
|
436
|
-
status, body = call(url, form, headers)
|
|
473
|
+
status, body, answered = call(url, form, headers)
|
|
474
|
+
trace = record_trace(answered, call: form.key?(:token) ? "revoke" : form[:grant_type].to_s, status:)
|
|
437
475
|
json = parse(body)
|
|
438
476
|
# A revoke (allow_empty) is confirmed by any 2xx, a 204 included; a token answer must be a 200 with a body.
|
|
439
477
|
return json if allow_empty ? (200..299).cover?(status) : (status == 200 && json.any?)
|
|
440
478
|
|
|
441
|
-
raise_for(status, json)
|
|
479
|
+
raise_for(status, json, trace)
|
|
442
480
|
end
|
|
443
481
|
|
|
444
|
-
def raise_for(status, json)
|
|
482
|
+
def raise_for(status, json, trace = nil)
|
|
445
483
|
detail = json["error_description"].to_s.lines.first.to_s.strip
|
|
446
484
|
detail = (json["error"] || json["message"] || json["errorMessage"]).to_s if detail.empty?
|
|
447
485
|
detail = "no detail" if detail.empty?
|
|
448
|
-
|
|
449
|
-
raise
|
|
486
|
+
traced = { trace_header:, trace_id: trace }
|
|
487
|
+
raise RateLimited.new("#{label} is throttling this app (#{status}); try again in a few minutes", **traced) if rate_limited_statuses.include?(status)
|
|
488
|
+
raise Revoked.new("#{label} no longer accepts this connection (#{detail}); connect again", **traced) if revoked?(status, json, detail)
|
|
450
489
|
|
|
451
|
-
raise Error
|
|
490
|
+
raise Error.new("#{label} answered #{status}: #{detail}", **traced)
|
|
452
491
|
end
|
|
453
492
|
|
|
454
493
|
def revoked?(status, json, detail)
|
|
@@ -464,6 +503,8 @@ module Studio
|
|
|
464
503
|
{}
|
|
465
504
|
end
|
|
466
505
|
|
|
506
|
+
# [status, body, response headers]. A stand-in may answer [status, body]
|
|
507
|
+
# or [status, body, { "header" => "value" }].
|
|
467
508
|
def call(url, form, headers)
|
|
468
509
|
return http.call(url, form, headers) if http
|
|
469
510
|
|
|
@@ -474,7 +515,7 @@ module Studio
|
|
|
474
515
|
headers.each { |name, value| request[name] = value }
|
|
475
516
|
request.body = headers["Content-Type"] == "application/json" ? JSON.generate(form) : URI.encode_www_form(form)
|
|
476
517
|
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 20) { _1.request(request) }
|
|
477
|
-
[response.code.to_i, response.body]
|
|
518
|
+
[response.code.to_i, response.body, response]
|
|
478
519
|
rescue *NETWORK_ERRORS => e
|
|
479
520
|
raise Error, "#{label} could not be reached: #{e.class}"
|
|
480
521
|
end
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Studio
|
|
4
|
+
module Integrations
|
|
5
|
+
# EGNYTE, the connection only. A host's readers (folders, files) are its
|
|
6
|
+
# own; they call Studio.integration(:egnyte).api_base(connection).
|
|
7
|
+
#
|
|
8
|
+
# * Every Egnyte domain answers on its own host, <domain>.egnyte.com, so
|
|
9
|
+
# the admin types the domain at Connect (a POST, CSRF-checked). It is
|
|
10
|
+
# normalized ("Acme", "acme.egnyte.com" and "https://acme.egnyte.com/"
|
|
11
|
+
# are all "acme") and held to a DNS label before it reaches a URL.
|
|
12
|
+
# * One scope, Egnyte.filesystem, on the authorize URL and the exchange.
|
|
13
|
+
# The sign-in page and the token endpoint share one path.
|
|
14
|
+
# * CACHED tokens: the access token lives 30 days and Egnyte asks callers
|
|
15
|
+
# to cache it (its token endpoint allows about 100 requests an hour), so
|
|
16
|
+
# the row keeps it and refreshes only within a day of its expiry or after
|
|
17
|
+
# a 401. A refresh answers a new pair, stored before use.
|
|
18
|
+
# * The revoke takes the token and the client secret, not the id.
|
|
19
|
+
# * The token endpoint throttles with a 409 (and the API with a 429); an
|
|
20
|
+
# "invalid refresh token" detail means the grant is gone.
|
|
21
|
+
#
|
|
22
|
+
# Checked against the hub's Egnyte::OAuthClient, EgnyteConnection and
|
|
23
|
+
# Egnyte::Reader (mcritchie-studio), which cite Egnyte's authentication docs.
|
|
24
|
+
module Egnyte
|
|
25
|
+
HOST_SUFFIX = ".egnyte.com"
|
|
26
|
+
TOKEN_PATH = "/puboauth/token"
|
|
27
|
+
REVOKE_PATH = "/pubapi/v1/tokens/revoke"
|
|
28
|
+
API_PATH = "/pubapi/v1"
|
|
29
|
+
SCOPE = "Egnyte.filesystem"
|
|
30
|
+
# A DNS label: what may stand before .egnyte.com. Nothing else reaches a URL.
|
|
31
|
+
DOMAIN = /\A[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\z/
|
|
32
|
+
|
|
33
|
+
def self.host(domain) = "https://#{domain}#{HOST_SUFFIX}"
|
|
34
|
+
|
|
35
|
+
# The bare domain from what an admin typed, lower-cased (still unchecked).
|
|
36
|
+
def self.normalize(value)
|
|
37
|
+
value.to_s.strip.downcase.sub(%r{\Ahttps?://}, "").sub(%r{[/?#].*\z}, "").delete_suffix(HOST_SUFFIX)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
Integrations.register :egnyte,
|
|
41
|
+
label: "Egnyte",
|
|
42
|
+
summary: "An Egnyte domain's files, read with a user's own sign-in.",
|
|
43
|
+
connection: {
|
|
44
|
+
authorize_url: ->(domain) { "#{Egnyte.host(domain)}#{TOKEN_PATH}" },
|
|
45
|
+
token_url: ->(domain) { "#{Egnyte.host(domain)}#{TOKEN_PATH}" },
|
|
46
|
+
revoke_url: ->(domain) { "#{Egnyte.host(domain)}#{REVOKE_PATH}" },
|
|
47
|
+
scopes: [SCOPE], exchange_params: { scope: SCOPE },
|
|
48
|
+
client_auth: :form, revoke_auth: :secret_only,
|
|
49
|
+
refresh: :cached, refresh_margin: 1.day,
|
|
50
|
+
account: :connect, account_param: "egnyte_domain", account_format: DOMAIN,
|
|
51
|
+
normalize_account: ->(value) { Egnyte.normalize(value) },
|
|
52
|
+
rate_limited_statuses: [409, 429], revoked_pattern: /invalid refresh token|invalid_grant/i,
|
|
53
|
+
refusal_hint: "Check the developer key's redirect URI, then start again."
|
|
54
|
+
},
|
|
55
|
+
account_label: "Egnyte domain",
|
|
56
|
+
account_hint: "yourcompany (from yourcompany.egnyte.com)",
|
|
57
|
+
describe: lambda { |_integration, grant:, account:, get:|
|
|
58
|
+
token = grant["access_token"].to_s
|
|
59
|
+
next {} if token.empty?
|
|
60
|
+
|
|
61
|
+
username = get.call("#{Egnyte.host(account)}#{API_PATH}/whoami", token)["username"].to_s.strip
|
|
62
|
+
{ metadata: username.empty? ? {} : { "username" => username } }
|
|
63
|
+
},
|
|
64
|
+
default_label: ->(domain) { "#{domain}#{HOST_SUFFIX}" },
|
|
65
|
+
api_base: ->(_integration, connection) { "#{Egnyte.host(connection.account_id)}#{API_PATH}" },
|
|
66
|
+
stand_in: { answer: { "username" => "stand-in" } }
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Studio
|
|
4
|
+
module Integrations
|
|
5
|
+
# MICROSOFT 365 (Microsoft Graph, app-only), the connection only. A host's
|
|
6
|
+
# readers (users, teams, sites) are its own; they call
|
|
7
|
+
# Studio.integration(:microsoft_365).api_base(connection) with a token from
|
|
8
|
+
# Studio.connection(:microsoft_365).access_token(connection).
|
|
9
|
+
#
|
|
10
|
+
# * A tenant administrator approves the app at Microsoft's admin-consent
|
|
11
|
+
# page (common: the tenant is not known until they sign in). Microsoft
|
|
12
|
+
# comes back with ?tenant=<GUID>&admin_consent=True; anything but an
|
|
13
|
+
# approval refuses the callback.
|
|
14
|
+
# * The tenant id is private: stored only encrypted, the row keyed by a
|
|
15
|
+
# digest, the callback's tenant param kept out of the logs by exact
|
|
16
|
+
# key. It is lower-cased, so one tenant never makes two rows.
|
|
17
|
+
# * CLIENT CREDENTIALS on the tenant's own token endpoint, with the Graph
|
|
18
|
+
# .default scope (the application permissions the app registration
|
|
19
|
+
# lists). No refresh token exists: the access token lives in this
|
|
20
|
+
# process's memory only, per tenant.
|
|
21
|
+
# * unauthorized_client means the app is not found in, or not enabled
|
|
22
|
+
# for, the tenant: the grant is gone.
|
|
23
|
+
# * NO REVOKE endpoint: consent is removed in the tenant's admin center.
|
|
24
|
+
#
|
|
25
|
+
# Checked against the hub's Msgraph::OAuthClient and Msgraph::Reader
|
|
26
|
+
# (mcritchie-studio), which cite Microsoft's identity-platform docs.
|
|
27
|
+
module Microsoft365
|
|
28
|
+
LOGIN_HOST = "https://login.microsoftonline.com"
|
|
29
|
+
AUTHORIZE_URL = "#{LOGIN_HOST}/common/adminconsent"
|
|
30
|
+
SCOPE = "https://graph.microsoft.com/.default"
|
|
31
|
+
API_URL = "https://graph.microsoft.com/v1.0"
|
|
32
|
+
TENANT_ID = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/
|
|
33
|
+
|
|
34
|
+
Integrations.register :microsoft_365,
|
|
35
|
+
label: "Microsoft 365",
|
|
36
|
+
summary: "A Microsoft 365 tenant, read app-only after an administrator approves the app.",
|
|
37
|
+
connection: {
|
|
38
|
+
grant: :client_credentials,
|
|
39
|
+
authorize_url: AUTHORIZE_URL,
|
|
40
|
+
token_url: ->(tenant) { "#{LOGIN_HOST}/#{tenant}/oauth2/v2.0/token" },
|
|
41
|
+
scopes: [SCOPE],
|
|
42
|
+
account: :callback, account_param: "tenant", account_format: TENANT_ID,
|
|
43
|
+
normalize_account: ->(value) { value.to_s.strip.downcase },
|
|
44
|
+
private_account: true, filter_keys: %w[tenant],
|
|
45
|
+
revoked_errors: %w[unauthorized_client],
|
|
46
|
+
declined_errors: %w[access_denied permission_denied consent_required],
|
|
47
|
+
callback_check: lambda { |params|
|
|
48
|
+
"Microsoft did not report an approval. Nothing was connected." unless params[:admin_consent].to_s.casecmp?("true")
|
|
49
|
+
},
|
|
50
|
+
refusal_hint: "A tenant bought through a reseller may block the approval; otherwise check the app registration's redirect URI, then start again.",
|
|
51
|
+
revoke_note: "Remove the app in the tenant's Microsoft Entra admin center (Enterprise applications) to revoke its access there."
|
|
52
|
+
},
|
|
53
|
+
describe: lambda { |integration, grant:, account:, get:|
|
|
54
|
+
token = integration.provider.access_token(account)
|
|
55
|
+
{ label: get.call("#{API_URL}/organization/#{account}", token)["displayName"] }
|
|
56
|
+
},
|
|
57
|
+
default_label: ->(_tenant) { "Microsoft 365 tenant" },
|
|
58
|
+
api_base: ->(_integration, _connection) { API_URL },
|
|
59
|
+
stand_in: { callback_params: { tenant: "00000000-0000-0000-0000-000000000000", admin_consent: "True" },
|
|
60
|
+
answer: { "displayName" => "Stand-in Tenant" } }
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Studio
|
|
4
|
+
module Integrations
|
|
5
|
+
# QUICKBOOKS ONLINE (Intuit), the connection only. A host's readers (company
|
|
6
|
+
# info, reports) are its own; they call Studio.integration(:quickbooks).api_base(connection).
|
|
7
|
+
#
|
|
8
|
+
# * Sign-in at Intuit's app center. The endpoints come from Intuit's
|
|
9
|
+
# discovery document
|
|
10
|
+
# (https://developer.api.intuit.com/.well-known/openid_configuration),
|
|
11
|
+
# the same for sandbox and production.
|
|
12
|
+
# * The token and revoke calls authenticate with HTTP Basic; the revoke
|
|
13
|
+
# body is JSON.
|
|
14
|
+
# * CACHED access token, refreshed when it expires: Intuit's access token
|
|
15
|
+
# lives about an hour (expires_in 3600). The row keeps it, encrypted,
|
|
16
|
+
# with its expiry, and reuses it until 5 minutes before that expiry, or
|
|
17
|
+
# until the API answers 401 (fresh_access_token(stale: token)). Then it
|
|
18
|
+
# refreshes ONCE under the row's lock, reloading the row first, so a
|
|
19
|
+
# racing caller waits and reads the new token instead of spending the
|
|
20
|
+
# refresh token twice. A reader that still gets a 401 after that one
|
|
21
|
+
# refresh asks the admin to connect again; it never loops.
|
|
22
|
+
# * The refresh token ROTATES and the newest must be kept: every refresh
|
|
23
|
+
# answer must carry one (rotation: :required, else nothing is stored and
|
|
24
|
+
# the refresh refuses), and it is stored, with the access token and
|
|
25
|
+
# x_refresh_token_expires_in, before the access token is used.
|
|
26
|
+
# * invalid_grant on a refresh is a revoked grant: connect again.
|
|
27
|
+
# * intuit_tid: Intuit names every answer with this response header, and
|
|
28
|
+
# asks apps to keep it for support. It is read from every token
|
|
29
|
+
# exchange, refresh, revoke and describe answer, logged with the call
|
|
30
|
+
# (no token), kept as provider.last_trace_id, and carried by every error
|
|
31
|
+
# raised (Error#trace_id, and in its message, so the error log has it).
|
|
32
|
+
# Host readers call provider.record_trace(response, call:, status:).
|
|
33
|
+
# * The company is named on the callback (?realmId=), a number, kept out
|
|
34
|
+
# of the logs by exact key.
|
|
35
|
+
# * The environment setting (sandbox, the default, or production) says
|
|
36
|
+
# which Intuit keys these are, so which API host a new connection reads;
|
|
37
|
+
# anything but "production" is the sandbox, so a typo never points
|
|
38
|
+
# sandbox keys at live books. It is stored on the connection.
|
|
39
|
+
#
|
|
40
|
+
# Checked against the hub's Quickbooks::OAuthClient and Quickbooks::Reader
|
|
41
|
+
# (mcritchie-studio), which cite Intuit's documents.
|
|
42
|
+
module Quickbooks
|
|
43
|
+
AUTHORIZE_URL = "https://appcenter.intuit.com/connect/oauth2"
|
|
44
|
+
TOKEN_URL = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer"
|
|
45
|
+
REVOKE_URL = "https://developer.api.intuit.com/v2/oauth2/tokens/revoke"
|
|
46
|
+
SCOPE = "com.intuit.quickbooks.accounting"
|
|
47
|
+
API_URLS = { "sandbox" => "https://sandbox-quickbooks.api.intuit.com",
|
|
48
|
+
"production" => "https://quickbooks.api.intuit.com" }.freeze
|
|
49
|
+
# Intuit retired minor versions 1-74 in August 2025: 75 is the floor.
|
|
50
|
+
MINOR_VERSION = 75
|
|
51
|
+
REALM_ID = /\A\d{1,20}\z/
|
|
52
|
+
|
|
53
|
+
def self.api_url(environment) = API_URLS.fetch(environment.to_s, API_URLS.fetch("sandbox"))
|
|
54
|
+
|
|
55
|
+
Integrations.register :quickbooks,
|
|
56
|
+
label: "QuickBooks",
|
|
57
|
+
summary: "A QuickBooks Online company, read with its owner's sign-in.",
|
|
58
|
+
connection: {
|
|
59
|
+
authorize_url: AUTHORIZE_URL, token_url: TOKEN_URL, revoke_url: REVOKE_URL,
|
|
60
|
+
scopes: [SCOPE],
|
|
61
|
+
client_auth: :basic, revoke_format: :json,
|
|
62
|
+
refresh: :cached, refresh_margin: 5.minutes, rotation: :required,
|
|
63
|
+
refresh_expires_in_key: "x_refresh_token_expires_in",
|
|
64
|
+
account: :callback, account_param: "realmId", account_format: REALM_ID,
|
|
65
|
+
filter_keys: %w[realmId], trace_header: "intuit_tid",
|
|
66
|
+
refusal_hint: "Check the Intuit app's redirect URI, then start again."
|
|
67
|
+
},
|
|
68
|
+
settings: { environment: { values: %w[sandbox production], default: "sandbox" } },
|
|
69
|
+
metadata: ->(integration) { { "environment" => integration.setting(:environment) } },
|
|
70
|
+
describe: lambda { |integration, grant:, account:, get:|
|
|
71
|
+
token = grant["access_token"].to_s
|
|
72
|
+
next {} if token.empty?
|
|
73
|
+
|
|
74
|
+
base = "#{Quickbooks.api_url(integration.setting(:environment))}/v3/company/#{account}"
|
|
75
|
+
info = get.call("#{base}/companyinfo/#{account}?minorversion=#{MINOR_VERSION}", token)["CompanyInfo"]
|
|
76
|
+
{ label: info.is_a?(Hash) ? info["CompanyName"] : nil }
|
|
77
|
+
},
|
|
78
|
+
default_label: ->(_account) { "QuickBooks company" },
|
|
79
|
+
api_base: lambda { |_integration, connection|
|
|
80
|
+
"#{Quickbooks.api_url(connection.metadata.to_h['environment'])}/v3/company/#{connection.account_id}"
|
|
81
|
+
},
|
|
82
|
+
stand_in: { callback_params: { realmId: "1000000001" },
|
|
83
|
+
answer: { "CompanyInfo" => { "CompanyName" => "Stand-in Company" } } }
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "openssl"
|
|
5
|
+
require "uri"
|
|
6
|
+
require "json"
|
|
7
|
+
|
|
8
|
+
module Studio
|
|
9
|
+
# INTEGRATIONS: the engine's registry of integration CONNECTION definitions
|
|
10
|
+
# (docs/INTEGRATIONS.md), on top of the generic connection tooling
|
|
11
|
+
# (Studio::Connections, docs/CONNECTIONS.md).
|
|
12
|
+
#
|
|
13
|
+
# The engine ships one definition per integration it knows (QuickBooks,
|
|
14
|
+
# Egnyte, Microsoft 365). A definition holds the connection only: the URLs,
|
|
15
|
+
# the scopes, the token behaviour, and a minimal describe that names the
|
|
16
|
+
# account just connected (the company, the user, the organization). It holds
|
|
17
|
+
# NO reader and makes no business-data call: a host writes its own readers
|
|
18
|
+
# and plugs them into the integration's page with a panel.
|
|
19
|
+
#
|
|
20
|
+
# A host turns one on with one line in an initializer, naming its own env vars:
|
|
21
|
+
#
|
|
22
|
+
# Studio.enable_integration :quickbooks,
|
|
23
|
+
# env: { client_id: "INTUIT_CLIENT_ID", client_secret: "INTUIT_CLIENT_SECRET",
|
|
24
|
+
# environment: "INTUIT_ENVIRONMENT" },
|
|
25
|
+
# panel: "admin/integrations/quickbooks_panel"
|
|
26
|
+
#
|
|
27
|
+
# and mounts the admin page with Studio.draw_integrations_routes. An enabled
|
|
28
|
+
# integration stays off (Connect says which env vars are missing) until its
|
|
29
|
+
# client id and secret are set.
|
|
30
|
+
module Integrations
|
|
31
|
+
# Seconds to open the describe call's connection, and to read its answer.
|
|
32
|
+
OPEN_TIMEOUT = 10
|
|
33
|
+
READ_TIMEOUT = 20
|
|
34
|
+
|
|
35
|
+
# One integration the engine knows: the connection only.
|
|
36
|
+
#
|
|
37
|
+
# key the integration's key, and its connection's
|
|
38
|
+
# label the name on the page and every message
|
|
39
|
+
# summary one line on the page: what connecting it gives the host
|
|
40
|
+
# connection the Studio::Connections::Provider options, every one but
|
|
41
|
+
# env:, label: and describe:
|
|
42
|
+
# settings extra env vars a host may name besides the client id and
|
|
43
|
+
# secret: { name: { values: [...], default: "..." } }; a
|
|
44
|
+
# value outside `values` reads as the default
|
|
45
|
+
# account_label the Connect form's field label (account: :connect only)
|
|
46
|
+
# account_hint its placeholder
|
|
47
|
+
# metadata ->(integration) { Hash }: stored on every new connection,
|
|
48
|
+
# with no network call (the provider environment)
|
|
49
|
+
# describe ->(integration, grant:, account:, get:) { { label:, metadata: } }:
|
|
50
|
+
# names the account just connected with ONE call through
|
|
51
|
+
# `get` (->(url, token) { JSON Hash }); a Connections::Error
|
|
52
|
+
# there stores the connection under default_label
|
|
53
|
+
# default_label ->(account) { String }: the label when describe cannot say
|
|
54
|
+
# api_base ->(integration, connection) { String }: where the host's
|
|
55
|
+
# own readers send their calls for this connection
|
|
56
|
+
# stand_in { callback_params: {...}, answer: {...} }: what the
|
|
57
|
+
# stand-in's sign-in page sends back, and what its describe
|
|
58
|
+
# call answers (development and test only)
|
|
59
|
+
Definition = Struct.new(:key, :label, :summary, :connection, :settings, :account_label, :account_hint,
|
|
60
|
+
:metadata, :describe, :default_label, :api_base, :stand_in, keyword_init: true)
|
|
61
|
+
|
|
62
|
+
# The statuses an enabled integration can be in, in order.
|
|
63
|
+
STATUSES = {
|
|
64
|
+
not_set_up: "Not set up",
|
|
65
|
+
ready: "Ready to connect",
|
|
66
|
+
connected: "Connected"
|
|
67
|
+
}.freeze
|
|
68
|
+
|
|
69
|
+
class << self
|
|
70
|
+
# Adds a definition to the engine's catalog. The engine's own definitions
|
|
71
|
+
# register themselves when lib/studio/integrations/*.rb loads.
|
|
72
|
+
def register(key, **fields)
|
|
73
|
+
definition = Definition.new(key: key.to_s, settings: {}, metadata: ->(_integration) { {} },
|
|
74
|
+
default_label: nil, stand_in: {}, **fields)
|
|
75
|
+
definition.settings = definition.settings.to_h.transform_keys(&:to_sym)
|
|
76
|
+
lock.synchronize { catalog_map[definition.key] = definition.freeze }
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# Every integration the engine knows, enabled or not.
|
|
80
|
+
def catalog = lock.synchronize { catalog_map.values }
|
|
81
|
+
|
|
82
|
+
def definition(key)
|
|
83
|
+
lock.synchronize { catalog_map[key.to_s] } or
|
|
84
|
+
raise ArgumentError, "the engine has no integration #{key.to_s.inspect}; it knows #{catalog.map(&:key).join(', ')}"
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Turns an integration on: defines its connection (Studio.define_connection)
|
|
88
|
+
# with the host's env names, and adds it to the admin page.
|
|
89
|
+
def enable(key, env:, panel: nil, label: nil, scopes: nil)
|
|
90
|
+
integration = Integration.new(definition(key), env:, panel:, label:, scopes:)
|
|
91
|
+
lock.synchronize { enabled_map[integration.key] = integration }
|
|
92
|
+
integration
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# The enabled integrations, in the order the host enabled them.
|
|
96
|
+
def all = lock.synchronize { enabled_map.values }
|
|
97
|
+
|
|
98
|
+
def enabled?(key) = lock.synchronize { enabled_map.key?(key.to_s) }
|
|
99
|
+
|
|
100
|
+
def fetch(key)
|
|
101
|
+
lock.synchronize { enabled_map[key.to_s] } or raise ArgumentError, "the integration #{key.to_s.inspect} is not enabled"
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# Where draw_integrations_routes mounted the page ("admin/integrations").
|
|
105
|
+
attr_accessor :mount_path
|
|
106
|
+
|
|
107
|
+
# Forgets every enabled integration (not the catalog). Tests only.
|
|
108
|
+
def reset!
|
|
109
|
+
lock.synchronize do
|
|
110
|
+
enabled_map.clear
|
|
111
|
+
@mount_path = nil
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
private
|
|
116
|
+
|
|
117
|
+
def catalog_map = (@catalog_map ||= {})
|
|
118
|
+
def enabled_map = (@enabled_map ||= {})
|
|
119
|
+
def lock = (@lock ||= Monitor.new)
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# One integration a host enabled: its definition, the host's env names, its
|
|
123
|
+
# connection provider and the host's panel.
|
|
124
|
+
class Integration
|
|
125
|
+
attr_reader :definition, :env, :panel, :provider
|
|
126
|
+
|
|
127
|
+
# Stand-in for the describe call: (url, headers) -> [status, body]. nil
|
|
128
|
+
# means the provider itself. Refused outside development and test.
|
|
129
|
+
attr_reader :api_http
|
|
130
|
+
|
|
131
|
+
def initialize(definition, env:, panel: nil, label: nil, scopes: nil)
|
|
132
|
+
@definition = definition
|
|
133
|
+
@env = env.to_h.transform_keys(&:to_sym)
|
|
134
|
+
unknown = @env.keys - %i[client_id client_secret] - definition.settings.keys
|
|
135
|
+
raise ArgumentError, "#{key}: env names client_id, client_secret#{definition.settings.keys.map { ", #{_1}" }.join}; not #{unknown.join(', ')}" if unknown.any?
|
|
136
|
+
raise ArgumentError, "#{key}: env values are env var names (Strings)" unless @env.values.all?(String)
|
|
137
|
+
|
|
138
|
+
@panel = panel&.to_s
|
|
139
|
+
options = definition.connection.merge(
|
|
140
|
+
label: label || definition.label,
|
|
141
|
+
env: @env.slice(:client_id, :client_secret),
|
|
142
|
+
describe: ->(grant:, account:, provider:) { describe_account(grant:, account:) }
|
|
143
|
+
)
|
|
144
|
+
options[:scopes] = Array(scopes) if scopes
|
|
145
|
+
@provider = Studio.define_connection(definition.key, **options)
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def key = definition.key
|
|
149
|
+
def label = provider.label
|
|
150
|
+
def summary = definition.summary
|
|
151
|
+
|
|
152
|
+
# A setting's value from the host's env var: one of its values, else its default.
|
|
153
|
+
def setting(name)
|
|
154
|
+
spec = definition.settings.fetch(name.to_sym)
|
|
155
|
+
value = @env[name.to_sym] && ENV[@env[name.to_sym]].to_s.strip.downcase
|
|
156
|
+
spec[:values].include?(value) ? value : spec[:default]
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# Every connection of this integration this server can read, newest first.
|
|
160
|
+
def connections = Studio::Connection.readable(key)
|
|
161
|
+
|
|
162
|
+
# What keeps a Connect from starting here, as sentences (empty when none).
|
|
163
|
+
def missing
|
|
164
|
+
reasons = []
|
|
165
|
+
unless provider.connectable?
|
|
166
|
+
unset = provider.env_names.reject { |name| ENV[name].to_s.strip != "" }
|
|
167
|
+
reasons << "#{unset.join(' and ')} #{unset.one? ? 'is' : 'are'} not set."
|
|
168
|
+
end
|
|
169
|
+
reasons << "The app's Active Record encryption keys are not set." unless Studio::Connections.encryption_ready?
|
|
170
|
+
reasons
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# :not_set_up, :ready or :connected (STATUSES).
|
|
174
|
+
def status
|
|
175
|
+
return :not_set_up if missing.any?
|
|
176
|
+
|
|
177
|
+
connections.any? ? :connected : :ready
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def status_label = STATUSES.fetch(status)
|
|
181
|
+
|
|
182
|
+
# Where the host's readers send their calls for `connection`.
|
|
183
|
+
def api_base(connection) = definition.api_base.call(self, connection)
|
|
184
|
+
|
|
185
|
+
def api_http=(callable)
|
|
186
|
+
unless callable.nil? || Studio::Connections.seams_allowed?
|
|
187
|
+
raise Studio::Connections::Error, "#{label}: the describe stand-in is for tests, the e2e lane and a local demo (development and test only)"
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
@api_http = callable
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
# Stands the whole integration in: the provider's sign-in page and token
|
|
194
|
+
# endpoints (Studio::Connections::StandIn) and the describe call.
|
|
195
|
+
# Development and test only; refused anywhere else.
|
|
196
|
+
def install_stand_in!(access_lifetime: 3600)
|
|
197
|
+
answer = definition.stand_in.fetch(:answer, {}).to_json
|
|
198
|
+
self.api_http = ->(_url, _headers) { [200, answer] }
|
|
199
|
+
Studio::Connections::StandIn.install!(provider, callback_params: definition.stand_in.fetch(:callback_params, {}), access_lifetime:)
|
|
200
|
+
self
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
def uninstall_stand_in!
|
|
204
|
+
self.api_http = nil
|
|
205
|
+
Studio::Connections::StandIn.uninstall!(provider)
|
|
206
|
+
self
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
# The provider's describe hook: the definition's metadata, then its one
|
|
210
|
+
# describe call. A refusal there keeps the metadata and the default label.
|
|
211
|
+
def describe_account(grant:, account:)
|
|
212
|
+
metadata = definition.metadata.call(self).to_h
|
|
213
|
+
described = {}
|
|
214
|
+
if definition.describe
|
|
215
|
+
begin
|
|
216
|
+
described = definition.describe.call(self, grant:, account:, get: method(:describe_get)).to_h.symbolize_keys
|
|
217
|
+
rescue Studio::Connections::Error => e
|
|
218
|
+
# Kept in the error log (with the provider's trace id, when it names
|
|
219
|
+
# one), as a refused exchange is; the connection still stores.
|
|
220
|
+
begin
|
|
221
|
+
::ErrorLog.capture!(e) if defined?(::ErrorLog) && ::ErrorLog.respond_to?(:capture!)
|
|
222
|
+
rescue StandardError => log_error
|
|
223
|
+
Rails.logger.error("[studio_integration] describe #{key} refused (#{e.message}); ErrorLog write failed: #{log_error.class}")
|
|
224
|
+
end
|
|
225
|
+
end
|
|
226
|
+
end
|
|
227
|
+
label = described[:label].to_s.strip.presence || definition.default_label&.call(account)
|
|
228
|
+
{ label:, metadata: metadata.merge(described[:metadata].to_h) }.compact
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
private
|
|
232
|
+
|
|
233
|
+
# The describe call's one GET: a bearer token, JSON back. Raises
|
|
234
|
+
# Studio::Connections::Error (RateLimited on a 429) on anything but a 200.
|
|
235
|
+
def describe_get(url, token)
|
|
236
|
+
headers = { "Authorization" => "Bearer #{token}", "Accept" => "application/json" }
|
|
237
|
+
status, body, answered = api_http ? api_http.call(url, headers) : request(url, headers)
|
|
238
|
+
trace = provider.record_trace(answered, call: "describe", status:)
|
|
239
|
+
traced = { trace_header: provider.trace_header, trace_id: trace }
|
|
240
|
+
json = begin
|
|
241
|
+
JSON.parse(body.to_s)
|
|
242
|
+
rescue JSON::ParserError
|
|
243
|
+
{}
|
|
244
|
+
end
|
|
245
|
+
json = {} unless json.is_a?(Hash)
|
|
246
|
+
raise Studio::Connections::RateLimited.new("#{label} is throttling this app (429)", **traced) if status == 429
|
|
247
|
+
raise Studio::Connections::Error.new("#{label} answered #{status} to the describe call", **traced) unless status == 200
|
|
248
|
+
|
|
249
|
+
json
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
def request(url, headers)
|
|
253
|
+
uri = URI(url)
|
|
254
|
+
raise Studio::Connections::Error, "#{label}: a describe call must be https" unless uri.scheme == "https"
|
|
255
|
+
|
|
256
|
+
get = Net::HTTP::Get.new(uri)
|
|
257
|
+
headers.each { |name, value| get[name] = value }
|
|
258
|
+
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: OPEN_TIMEOUT, read_timeout: READ_TIMEOUT) { _1.request(get) }
|
|
259
|
+
[response.code.to_i, response.body, response]
|
|
260
|
+
rescue *Studio::Connections::NETWORK_ERRORS => e
|
|
261
|
+
raise Studio::Connections::Error, "#{label} could not be reached: #{e.class}"
|
|
262
|
+
end
|
|
263
|
+
end
|
|
264
|
+
end
|
|
265
|
+
end
|