studio-engine 0.136.0 → 0.137.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: 115dd9bf2e7e3c792cb86e876228dfb6fadbef20a10f431bb5a09103450f9329
4
- data.tar.gz: beab5d5a34b1e00418259a15616c89e520f8501537f1d4cd89fd4d76daed8936
3
+ metadata.gz: 448f5dc2b80db8f30bb9d05849d581065592b28f2189062424bfd26c25acdc63
4
+ data.tar.gz: 68b40d7dd6cbc3bc2f8c9e19f409755e1c7e1d1ece531e1689542f32fdeccb7c
5
5
  SHA512:
6
- metadata.gz: 259358f3215e90bda17d652259346d27544a41455648f6e521b8f1dca724390213cb48e063c8c05bc8ce9bbefadfd2b7e82a889d1c413b19543251d1398322a0
7
- data.tar.gz: e9b5676ada781b1dc23a008f986e16d7a088c120dd19e8f0e4777636f6ec61a3210b6d7d130f1a922113a4bd3baffa1c53bb462dffd88611b7d03e2a7b120fc1
6
+ metadata.gz: 93377b901882007a34b2bb4ffc855ed5078cfb02e8cc35a58e9afe102df2d832d046f7531d95996a4899259a6bbfe0359d6a64ebd32370e7ca8fb274a27cd3bb
7
+ data.tar.gz: 4781ef35c39d5cdde579d71cf8ad93e26abb5896895480aece83c315b2e944fc48b959b09589c34e6c62354dbe2d7aa1a7746980dafd299d24023e80e74a9ae8
data/CHANGELOG.md CHANGED
@@ -4,6 +4,12 @@ The format is [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). This pro
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.137.0 — 2026-11-08
8
+
9
+ ### Added
10
+
11
+ - **Connections: generic OAuth 2.0 connection tooling.** A host declares each provider it connects with `Studio.define_connection`: static or per-account endpoints with strict account validation, scopes, form or HTTP Basic client auth, and one of three refresh policies (`:rotating`, which refreshes and stores the new refresh token under the row's lock before use; `:cached`, which keeps the access token until near expiry; `:memory`, the client-credentials grant with no stored token). The engine gives it `Studio::Connection` (one `studio_connections` table, tokens encrypted; install with `bin/rails g studio:connections`), the connect, callback and disconnect actions (`Studio::ConnectionFlow`, or the engine's `Studio::ConnectionsController`) behind `Studio.connection_admin_guard`, `Studio.draw_connection_routes`, a log filter by exact key for the keys a provider names, and `Studio::Connections::StandIn` for the e2e lane. The engine names no provider, and nothing changes until a host declares one. See `docs/CONNECTIONS.md`.
12
+
7
13
  ## 0.136.0 — 2026-11-08
8
14
 
9
15
  ### Added
data/README.md CHANGED
@@ -51,6 +51,7 @@ resolved.
51
51
  - **Voice profile**: an opt-in row on `/profile` ("Set up your voice"): the person reads three phrases with a live level meter, their device turns each take into a speaker embedding (WeSpeaker via transformers.js), and only the averaged vector is saved on their user, never audio. `Studio::VoiceMatch.identify(embedding, among: User.all, model:)` answers who is speaking. Turn it on with `config.voice_profile = true` after installing the migration. See [`docs/VOICE_PROFILE.md`](docs/VOICE_PROFILE.md).
52
52
  - **Voice capture**: the microphone chip (names the microphone a page records from, picks another, Chrome help dialog), one level meter, and a record button that refuses a silent take and hands a heard one to the page as a `studio:voice-recorder:take` event with the blob; it uploads nothing. Render `studio/voice/microphone_chip` and `studio/voice/recorder`. See [`docs/VOICE_CAPTURE.md`](docs/VOICE_CAPTURE.md).
53
53
  - **Voice transcription**: `POST /voice/takes` (opt-in, `config.voice_transcription = true`) turns a signed-in user's take into `{text, speaker, score}`: a mock-first transcriber (OpenAI `gpt-4o-transcribe` in production, a mock elsewhere, a no-live-calls trap in every test environment) and `Studio::VoiceMatch` against the user's own saved voice. Nothing is kept. See [`docs/VOICE_TRANSCRIPTION.md`](docs/VOICE_TRANSCRIPTION.md).
54
+ - **Connections**: generic OAuth 2.0 tooling to connect a third-party account. A host declares each provider with `Studio.define_connection` (endpoints, static or per-account; scopes; form or HTTP Basic client auth; a rotating, cached or client-credentials refresh policy). The engine gives it `Studio::Connection` (one table, tokens encrypted, `bin/rails g studio:connections`), the connect, callback and disconnect actions (`Studio::ConnectionFlow`) behind the host's admin guard, `Studio.draw_connection_routes`, an exact-key log filter, and a stand-in for the e2e lane. The engine names no provider. See [`docs/CONNECTIONS.md`](docs/CONNECTIONS.md).
54
55
  - **Surveys**: define a survey in app code (`config/surveys/*.rb`, `Studio.define_survey`) with six question types — emoji scale, 1–5 rating, single and multiple choice, short and long text — and the engine serves it at `/surveys/:slug`: one question per screen, autosave, resume, keyboard shortcuts, and a no-JavaScript fallback. `config.on_survey_completed` and `config.survey_ref_resolver` let the app fire its own goals and attribute email arrivals. An admin panel at `/admin/surveys` breaks results down per question and exports CSV. Opt in with `config.draw_survey_routes = true` and `config.draw_admin_survey_routes = true`. See [`docs/SURVEYS.md`](docs/SURVEYS.md).
55
56
 
56
57
  ## Tailwind
@@ -254,6 +255,8 @@ Set `Studio.draw_booking_routes = true` to add the booking page (`GET /schedule`
254
255
 
255
256
  Set `Studio.draw_survey_routes = true` to add the public survey pages (`/surveys/:slug`, helper `studio_survey_path`) and `Studio.draw_admin_survey_routes = true` to add the admin results panel (`/admin/surveys`, helpers `admin_surveys_path` / `admin_survey_path`) — both off by default because an app may already own those paths. Both need the `studio_survey_responses` table ([`docs/SURVEYS.md`](docs/SURVEYS.md)).
256
257
 
258
+ For each connection provider a host declares, `Studio.draw_connection_routes(self, :files, path: "admin/files")` adds its connect (`GET`/`POST /admin/files/connect`), callback (`GET /admin/files/callback`, the redirect URI to register) and disconnect (`DELETE /admin/files/connections/:id`) routes. Nothing is drawn for a provider the host has not declared. They need the `studio_connections` table (`bin/rails g studio:connections`; [`docs/CONNECTIONS.md`](docs/CONNECTIONS.md)).
259
+
257
260
  **Magic links need the `studio_links` table.** Install it with `bin/rails studio_engine:install:migrations && bin/rails db:migrate` (install all of them) before enabling `:magic_link` — never by hand-copying the migration, which collides with the task's own copy on `class CreateStudioLinks`. Without the table, the first sign-in raises `Studio::Link::MissingTable`.
258
261
 
259
262
  Set `Studio.agent_chat_souls = %w[alex]` to add the shared agent chat's proxy (`POST /agent_chat/messages`, `GET /agent_chat/turns`), which forwards to the McRitchie Studio hub with the app's `AGENT_CHAT_TOKEN`; then `render "studio/agent_chat/chat", soul: "alex", name: "Alex", portrait: ...` on any page, with `voice: true` for hold to talk in the composer ([`docs/AGENT_CHAT.md`](docs/AGENT_CHAT.md)). To open that chat in a modal from any button, render `studio/agent_chat/talk_modal` once and mark the buttons with `studio_talk_to_agent_link` ([`docs/AGENT_CHAT.md`](docs/AGENT_CHAT.md), "Talk to an agent in a modal").
@@ -0,0 +1,215 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Studio
4
+ # The connect, callback and disconnect actions for any provider a host
5
+ # declared with Studio.define_connection (docs/CONNECTIONS.md). Included by
6
+ # Studio::ConnectionsController; a host includes it in its own admin
7
+ # controller instead when that controller also serves the provider's page
8
+ # (its `show`, with the provider's live read), and names that controller in
9
+ # Studio.draw_connection_routes.
10
+ #
11
+ # connect checks the encryption keys and the client, keeps a fresh OAuth
12
+ # state (and, for an account named before Connect, the checked
13
+ # account) in the session, and redirects to the provider
14
+ # callback checks the state first, then the provider's refusal, its own
15
+ # callback check and the account; exchanges the code (a code
16
+ # grant); names the account with the host's describe hook; and
17
+ # stores Studio::Connection. The account named before Connect
18
+ # is read from the session, never from the callback's query.
19
+ # disconnect revokes the grant at the provider when it has a revoke
20
+ # endpoint, forgets an in-memory token, deletes the row, and
21
+ # says whether the provider confirmed
22
+ #
23
+ # No token, and no part of one, is rendered, flashed or logged here. A
24
+ # refused exchange, describe or revoke is kept in the error log
25
+ # (Studio::ErrorHandling#rescue_and_log) as well as said on the page.
26
+ #
27
+ # WHO MAY: the host's admin guard, Studio.connection_admin_guard (a method
28
+ # name on the controller, :require_admin by default, or a callable taking
29
+ # the controller). WHERE IT COMES BACK: return_to, honoured only when it is
30
+ # exactly one of the route's return paths (never an open redirect).
31
+ module ConnectionFlow
32
+ extend ActiveSupport::Concern
33
+
34
+ included do
35
+ before_action :require_connection_admin
36
+ # The callback's URL carries a single-use code: no cache keeps the page.
37
+ before_action(only: :callback) { response.headers["Cache-Control"] = "no-store" }
38
+ end
39
+
40
+ def connect
41
+ provider = connection_provider
42
+ # An account typed at Connect is accepted only on a CSRF-checked POST,
43
+ # even when a host draws a GET route by hand.
44
+ return head(:method_not_allowed) if provider.account_source == :connect && !request.post?
45
+
46
+ back = connection_return_to(params[:return_to])
47
+ return redirect_to(back, alert: connection_encryption_message) unless Studio::Connections.encryption_ready?
48
+
49
+ account = nil
50
+ if provider.account_source == :connect
51
+ account = provider.normalize_account(params[provider.account_param]) or
52
+ return redirect_to(back, alert: "That is not a #{provider.label} account. Check what you entered, then press Connect again.")
53
+ end
54
+ url = provider.authorize_url(redirect_uri: connection_callback_url, state: new_connection_state, account:)
55
+ session[connection_session_key(:account)] = account
56
+ session[connection_session_key(:return_to)] = back
57
+ redirect_to url, allow_other_host: true
58
+ rescue Studio::Connections::NotConfigured
59
+ redirect_to back, alert: connection_keys_message
60
+ end
61
+
62
+ def callback
63
+ provider = connection_provider
64
+ expected = session.delete(connection_session_key(:state)).to_s
65
+ kept_account = session.delete(connection_session_key(:account))
66
+ back = connection_return_to(session.delete(connection_session_key(:return_to)))
67
+ account = provider.account_source == :connect ? provider.normalize_account(kept_account) : nil
68
+ unless connection_state_matches?(expected) && (provider.account_source != :connect || account)
69
+ return render(plain: "OAuth state mismatch: start the connection again.", status: :bad_request)
70
+ end
71
+
72
+ return redirect_to(back, alert: connection_refusal(provider, params[:error].to_s)) if params[:error].present?
73
+ return redirect_to(back, alert: connection_encryption_message) unless Studio::Connections.encryption_ready?
74
+
75
+ problem = provider.callback_check&.call(params)
76
+ return redirect_to(back, alert: problem.to_s) if problem.present?
77
+
78
+ if provider.account_source == :callback
79
+ account = provider.normalize_account(params[provider.account_param]) or
80
+ return redirect_to(back, alert: "#{provider.label} came back without naming a valid account. Nothing was connected; start again.")
81
+ end
82
+
83
+ grant = {}
84
+ if provider.grant == :authorization_code
85
+ grant = rescue_and_log(target: current_user) do
86
+ provider.exchange_code(code: params[:code].to_s, redirect_uri: connection_callback_url, account:)
87
+ end
88
+ end
89
+ described = describe_connection(provider, grant, account)
90
+ account ||= described[:account]
91
+ return redirect_to(back, alert: "#{provider.label} answered, but did not say which account it was. Nothing was connected.") if account.blank?
92
+
93
+ connection = rescue_and_log(target: current_user) do
94
+ Studio::Connection.store!(provider, grant, account:, by: connection_actor,
95
+ label: described[:label], metadata: described[:metadata] || {})
96
+ end
97
+ redirect_to back, notice: "#{provider.label} connected: #{connection.label}."
98
+ rescue ActiveRecord::RecordInvalid => e
99
+ redirect_to back, alert: "#{provider.label} answered, but the connection was not saved: #{e.record.errors.full_messages.to_sentence}."
100
+ rescue Studio::Connections::InvalidAccount
101
+ redirect_to back, alert: "#{provider.label} came back without naming a valid account. Nothing was connected; start again."
102
+ rescue Studio::Connections::NotConfigured
103
+ redirect_to back, alert: connection_keys_message
104
+ rescue Studio::Connections::Error => e
105
+ redirect_to back, alert: "#{provider.label} refused to exchange the sign-in code (#{e.message}). Start again: a code works once."
106
+ end
107
+
108
+ def disconnect
109
+ provider = connection_provider
110
+ back = connection_return_to(params[:return_to])
111
+ connection = Studio::Connection.for_provider(provider.key).find_by(id: params[:id])
112
+ return redirect_to(back, notice: "That #{provider.label} account was not connected, so nothing changed.", status: :see_other) unless connection
113
+
114
+ label = connection.label
115
+ revoked = revoke_connection(provider, connection)
116
+ rescue_and_log(target: current_user) do
117
+ provider.forget!(connection.account_id) if provider.refresh == :memory && connection.readable?
118
+ connection.destroy!
119
+ end
120
+ Rails.logger.info("[studio_connection] disconnect provider=#{provider.key} row=#{connection.id} " \
121
+ "by=#{connection_actor} at=#{Time.current.utc.iso8601} revoked=#{revoked.inspect}")
122
+ notice = case revoked
123
+ when true then "#{provider.label} disconnected for #{label}: #{provider.label} revoked the grant and the stored connection was deleted here."
124
+ when nil then "#{provider.label} disconnected for #{label}: the stored connection was deleted here. #{provider.revoke_note}"
125
+ else "#{provider.label} disconnected for #{label}: the stored connection was deleted here, but #{provider.label} did not confirm the revoke. #{provider.revoke_note}"
126
+ end
127
+ redirect_to back, notice:, status: :see_other
128
+ end
129
+
130
+ private
131
+
132
+ # The provider this request is for: the route's `studio_connection` default.
133
+ def connection_provider
134
+ @connection_provider ||= Studio::Connections.fetch(params[:studio_connection])
135
+ end
136
+
137
+ def connection_route = Studio::Connections.route(connection_provider.key)
138
+
139
+ # A method guard refuses the way a before_action does: it renders or
140
+ # redirects. A callable guard may do the same, or answer: false or nil
141
+ # refuses with 403, so `->(c) { c.current_user&.admin? }` is safe.
142
+ def require_connection_admin
143
+ guard = Studio.connection_admin_guard
144
+ return send(guard) unless guard.respond_to?(:call)
145
+
146
+ allowed = guard.call(self)
147
+ head(:forbidden) unless allowed || performed?
148
+ end
149
+
150
+ # Who connected it, as connected_by records: the user's slug, else their id.
151
+ def connection_actor
152
+ user = respond_to?(:current_user, true) ? current_user : nil
153
+ return nil unless user
154
+
155
+ (user.respond_to?(:slug) && user.slug.presence) || user.id.to_s
156
+ end
157
+
158
+ # The host's describe hook: { account:, label:, metadata: } for the account
159
+ # just connected (a whoami, a company name). A provider error there is kept
160
+ # in the error log and the connection stores under the provider's label.
161
+ def describe_connection(provider, grant, account)
162
+ return {} unless provider.describe
163
+
164
+ rescue_and_log(target: current_user) do
165
+ provider.describe.call(grant:, account:, provider:).to_h.symbolize_keys
166
+ end
167
+ rescue Studio::Connections::Error
168
+ {}
169
+ end
170
+
171
+ # True when the provider took the revoke, nil when it has no revoke
172
+ # endpoint, false when it refused or the row cannot be read.
173
+ def revoke_connection(provider, connection)
174
+ return nil unless provider.revocable?
175
+ return false unless connection.readable?
176
+
177
+ rescue_and_log(target: connection) { provider.revoke(connection) }
178
+ rescue Studio::Connections::Error
179
+ false
180
+ end
181
+
182
+ def connection_refusal(provider, code)
183
+ return "The sign-in was declined on #{provider.label}. Nothing was connected." if provider.declined_errors.include?(code)
184
+
185
+ "#{provider.label} refused the sign-in (#{code[0, 100]}). #{provider.refusal_hint}"
186
+ end
187
+
188
+ def connection_keys_message
189
+ "#{connection_provider.label} connections are not set up on this server: #{connection_provider.env_names.join(' and ')} are not set."
190
+ end
191
+
192
+ def connection_encryption_message
193
+ "This server cannot store a connection: its encryption keys are not set " \
194
+ "(#{Studio::Connections::ENCRYPTION_ENV.join(', ')}). Nothing was asked of #{connection_provider.label}."
195
+ end
196
+
197
+ def connection_return_to(value)
198
+ paths = connection_route.return_paths
199
+ paths.include?(value) ? value : paths.first
200
+ end
201
+
202
+ def connection_callback_url = public_send(:"#{connection_route.as}_callback_url")
203
+
204
+ def connection_session_key(name) = "studio_connection_#{connection_provider.key}_#{name}"
205
+
206
+ def connection_state_matches?(expected)
207
+ params[:state].present? && expected.present? &&
208
+ ActiveSupport::SecurityUtils.secure_compare(params[:state].to_s, expected)
209
+ end
210
+
211
+ def new_connection_state
212
+ SecureRandom.hex(16).tap { |state| session[connection_session_key(:state)] = state }
213
+ end
214
+ end
215
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Studio
4
+ # The engine's own home for a provider's connect, callback and disconnect
5
+ # (Studio::ConnectionFlow), for a host that serves the provider's page from
6
+ # elsewhere or not at all. Studio.draw_connection_routes points here unless
7
+ # the host names its own controller. It inherits the host's
8
+ # ApplicationController, so the host's layout, session, current_user and
9
+ # Studio::ErrorHandling (rescue_and_log, require_admin) apply.
10
+ class ConnectionsController < ::ApplicationController
11
+ include Studio::ConnectionFlow
12
+ end
13
+ end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Studio
4
+ # One third-party account a host app has connected over OAuth 2.0, for a
5
+ # provider the host declared with Studio.define_connection
6
+ # (Studio::Connections::Provider). docs/CONNECTIONS.md.
7
+ #
8
+ # One row per provider and account (account_key, unique within a provider).
9
+ # Connecting the same account again replaces its tokens (.store!). No token,
10
+ # and no part of one, is ever shown: every token column is encrypted, filtered
11
+ # from inspect, and read only by the provider's access_token.
12
+ #
13
+ # THE ROW DEPENDS ON THE APP'S ENCRYPTION KEYS: without them a connect refuses
14
+ # before it asks the provider for anything
15
+ # (Studio::Connections.encryption_ready?); with them lost or changed, a stored
16
+ # row is unreadable (#readable? is false), counts as not connected, and
17
+ # connecting again replaces it.
18
+ #
19
+ # ROTATION. #rotate! is called by the provider inside #with_lock, which
20
+ # reloads the row first: a racing caller waits, then spends the NEWEST
21
+ # refresh token, and the answered token is stored before the access token it
22
+ # came with is used.
23
+ class Connection < ApplicationRecord
24
+ self.table_name = "studio_connections"
25
+
26
+ encrypts :access_token, :refresh_token, :account_secret
27
+ self.filter_attributes += %i[access_token refresh_token account_secret account_key]
28
+
29
+ validates :provider, :account_key, :connected_at, presence: true
30
+ validates :account_key, uniqueness: { scope: :provider }
31
+ validate :holds_what_its_policy_needs
32
+
33
+ scope :for_provider, ->(key) { where(provider: key.to_s) }
34
+
35
+ class << self
36
+ def encryption_ready? = Studio::Connections.encryption_ready?
37
+
38
+ def newest_first = order(connected_at: :desc, id: :desc)
39
+
40
+ # Every connection of a provider whose tokens this server can read, newest first.
41
+ def readable(provider) = for_provider(provider).newest_first.select(&:readable?)
42
+
43
+ # Stores the account a connect reached. `grant` is the token endpoint's
44
+ # JSON ({} for a client-credentials consent). Raises InvalidAccount for an
45
+ # account that fails the provider's format, and RecordInvalid when the
46
+ # answer lacks what the provider's policy keeps; the message names the
47
+ # field, never a value.
48
+ def store!(provider, grant, account:, by:, label: nil, metadata: {}, now: Time.current)
49
+ provider = Studio::Connections.fetch(provider) unless provider.is_a?(Studio::Connections::Provider)
50
+ account = provider.normalize_account(account) or raise Studio::Connections::InvalidAccount, "not a #{provider.label} account"
51
+ key = provider.account_key_for(account)
52
+
53
+ transaction(requires_new: true) do
54
+ connection = find_or_initialize_by(provider: provider.key, account_key: key)
55
+ # A row whose tokens can no longer be read is replaced, not updated.
56
+ unless connection.new_record? || connection.readable?
57
+ where(id: connection.id).delete_all
58
+ connection = new(provider: provider.key, account_key: key)
59
+ end
60
+ keep_access = provider.refresh == :cached
61
+ connection.assign_attributes(
62
+ account_secret: provider.private_account ? account : nil,
63
+ label: label.to_s.strip.presence || provider.label,
64
+ access_token: keep_access ? grant["access_token"].to_s.presence : nil,
65
+ refresh_token: provider.refresh == :memory ? nil : grant["refresh_token"].to_s.presence,
66
+ access_expires_at: keep_access ? Studio::Connections::Provider.expiry(grant, "expires_in", now) : nil,
67
+ refresh_expires_at: Studio::Connections::Provider.expiry(grant, provider.refresh_expires_in_key, now),
68
+ metadata: metadata.to_h.deep_stringify_keys, connected_by: by.to_s.presence, connected_at: now,
69
+ last_refreshed_at: nil
70
+ )
71
+ connection.save!
72
+ connection
73
+ end
74
+ end
75
+ end
76
+
77
+ def provider_definition = Studio::Connections.fetch(provider)
78
+
79
+ # The account as the provider names it: the decrypted id for a private
80
+ # account, else the key itself.
81
+ def account_id = account_secret.presence || account_key
82
+
83
+ # An access token, by the provider's refresh policy. `stale:` is a token the
84
+ # API just refused with a 401 (the :cached policy refreshes it).
85
+ def fresh_access_token(stale: nil) = provider_definition.access_token(self, stale:)
86
+
87
+ # Can the stored tokens be decrypted with this app's keys?
88
+ def readable?
89
+ access_token
90
+ refresh_token
91
+ account_secret
92
+ true
93
+ rescue ActiveRecord::Encryption::Errors::Base
94
+ false
95
+ end
96
+
97
+ # Is the stored access token good for longer than the provider's margin? A
98
+ # token with no expiry is, until the provider refuses it.
99
+ def access_fresh?(now = Time.current)
100
+ return false if access_token.blank?
101
+
102
+ access_expires_at.nil? || access_expires_at > now + provider_definition.refresh_margin
103
+ end
104
+
105
+ # Stores what a refresh just answered. Called inside #with_lock by the
106
+ # provider, before the access token is used. A provider whose rotation is
107
+ # :required refuses an answer without a refresh token (storing nothing would
108
+ # lose the account); otherwise a blank one keeps the stored one.
109
+ def rotate!(grant, now: Time.current)
110
+ definition = provider_definition
111
+ answered = grant["refresh_token"].to_s.presence
112
+ if answered.nil? && definition.rotation == :required
113
+ raise Studio::Connections::Error, "#{definition.label} answered a refresh with no refresh token; connect again"
114
+ end
115
+
116
+ changes = { refresh_token: answered || refresh_token, last_refreshed_at: now,
117
+ refresh_expires_at: Studio::Connections::Provider.expiry(grant, definition.refresh_expires_in_key, now) || refresh_expires_at }
118
+ if definition.refresh == :cached
119
+ raise Studio::Connections::Error, "#{definition.label} answered a refresh with no access token" if grant["access_token"].blank?
120
+
121
+ changes.merge!(access_token: grant["access_token"], access_expires_at: Studio::Connections::Provider.expiry(grant, "expires_in", now))
122
+ end
123
+ update!(changes)
124
+ end
125
+
126
+ private
127
+
128
+ def holds_what_its_policy_needs
129
+ definition = Studio::Connections.defined?(provider) ? Studio::Connections.fetch(provider) : nil
130
+ return errors.add(:provider, "is not a defined connection provider") unless definition
131
+
132
+ errors.add(:refresh_token, :blank) if definition.refresh == :rotating && refresh_token.blank?
133
+ errors.add(:access_token, :blank) if definition.refresh == :cached && access_token.blank?
134
+ errors.add(:account_secret, :blank) if definition.private_account && account_secret.blank?
135
+ end
136
+ end
137
+ end
@@ -0,0 +1,35 @@
1
+ # CONNECTIONS (docs/CONNECTIONS.md): one row per third-party account a host app
2
+ # has connected over OAuth 2.0, for any provider the host declares with
3
+ # Studio.define_connection. The engine names no provider; `provider` is the
4
+ # host's key for one.
5
+ #
6
+ # One row per provider and account (`account_key`, unique within a provider):
7
+ # the account itself (a domain, a company id), or a keyed digest of it when the
8
+ # provider declares the account private, in which case the id is kept only in
9
+ # `account_secret`, encrypted. Every token column is encrypted with the app's
10
+ # Active Record encryption keys; a host without them cannot store a row.
11
+ #
12
+ # Installing the table changes nothing on its own: no route is drawn and no
13
+ # provider exists until the host declares one.
14
+ class CreateStudioConnections < ActiveRecord::Migration[7.2]
15
+ def change
16
+ create_table :studio_connections do |t|
17
+ t.string :provider, null: false
18
+ t.string :account_key, null: false
19
+ t.text :account_secret
20
+ t.string :label
21
+ t.text :access_token
22
+ t.text :refresh_token
23
+ t.datetime :access_expires_at
24
+ t.datetime :refresh_expires_at
25
+ t.json :metadata, null: false, default: {}
26
+ t.string :connected_by
27
+ t.datetime :connected_at, null: false
28
+ t.datetime :last_refreshed_at
29
+
30
+ t.timestamps
31
+ end
32
+
33
+ add_index :studio_connections, [:provider, :account_key], unique: true
34
+ end
35
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module Studio
6
+ module Generators
7
+ # Adopt the connections tooling (docs/CONNECTIONS.md) in one repeatable step:
8
+ #
9
+ # bin/rails g studio:connections
10
+ # bin/rails db:migrate
11
+ #
12
+ # What it does, each step idempotent (a second run changes nothing):
13
+ #
14
+ # 1. copies the engine's studio_connections migration into db/migrate,
15
+ # in exactly the form `studio_engine:install:migrations` writes (so that
16
+ # task later sees it and skips it), and ONLY that migration;
17
+ # 2. writes config/initializers/studio_connections.rb, a commented example
18
+ # provider to fill in, unless the file exists.
19
+ #
20
+ # It declares no provider and draws no route: the host names each provider
21
+ # it connects, and its routes, itself.
22
+ class ConnectionsGenerator < Rails::Generators::Base
23
+ MIGRATION_NAME = "create_studio_connections"
24
+ ENGINE_SCOPE = "studio_engine"
25
+ INITIALIZER = "config/initializers/studio_connections.rb"
26
+
27
+ def copy_migration
28
+ existing = Dir.glob(File.join(destination_root, "db/migrate/*_#{MIGRATION_NAME}{,.#{ENGINE_SCOPE}}.rb"))
29
+ if existing.any?
30
+ say_status :identical, existing.first.delete_prefix("#{destination_root}/"), :blue
31
+ return
32
+ end
33
+
34
+ source = self.class.engine_migration
35
+ original_version = File.basename(source)[/\A\d+/]
36
+ body = "# This migration comes from #{ENGINE_SCOPE} (originally #{original_version})\n#{File.read(source)}"
37
+ create_file "db/migrate/#{self.class.next_version}_#{MIGRATION_NAME}.#{ENGINE_SCOPE}.rb", body
38
+ end
39
+
40
+ def write_initializer
41
+ if File.exist?(File.join(destination_root, INITIALIZER))
42
+ say_status :identical, INITIALIZER, :blue
43
+ return
44
+ end
45
+
46
+ create_file INITIALIZER, INITIALIZER_BODY
47
+ end
48
+
49
+ def next_steps
50
+ say <<~TEXT
51
+
52
+ Connections installed. Next:
53
+ bin/rails db:migrate
54
+ Declare each provider in #{INITIALIZER}, then draw its routes in config/routes.rb:
55
+ Studio.draw_connection_routes(self, :files, path: "admin/files", controller: "admin/files")
56
+ Set the provider's client id and secret, and the app's Active Record encryption keys.
57
+ TEXT
58
+ end
59
+
60
+ def self.engine_migration
61
+ File.expand_path("../../../../db/migrate/20261108130000_#{MIGRATION_NAME}.rb", __dir__)
62
+ end
63
+
64
+ def self.next_version
65
+ Time.now.utc.strftime("%Y%m%d%H%M%S")
66
+ end
67
+
68
+ INITIALIZER_BODY = <<~RUBY
69
+ # frozen_string_literal: true
70
+
71
+ # Connections (studio-engine docs/CONNECTIONS.md). One Studio.define_connection
72
+ # per provider this app connects; each stays off until its client id and
73
+ # secret are set. Draw its routes in config/routes.rb with
74
+ # Studio.draw_connection_routes. The example below is a placeholder: no
75
+ # such provider exists.
76
+ #
77
+ # Studio.define_connection :files,
78
+ # label: "Example Files",
79
+ # env: { client_id: "EXAMPLE_FILES_CLIENT_ID", client_secret: "EXAMPLE_FILES_CLIENT_SECRET" },
80
+ # authorize_url: "https://files.example/oauth/authorize",
81
+ # token_url: "https://files.example/oauth/token",
82
+ # revoke_url: "https://files.example/oauth/revoke",
83
+ # scopes: %w[files.read],
84
+ # refresh: :rotating,
85
+ # account: :callback, account_param: "account_id", account_format: /\\A\\d{1,20}\\z/,
86
+ # filter_keys: %w[account_id]
87
+ #
88
+ # Who may connect (default: :require_admin from Studio::ErrorHandling):
89
+ # Studio.connection_admin_guard = :require_admin
90
+ RUBY
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Studio
6
+ module Connections
7
+ # A STAND-IN PROVIDER for the e2e lane and a local demo: a host walks a
8
+ # connection with no client registered at the provider. NEVER production
9
+ # (the Provider seams refuse it there).
10
+ #
11
+ # Studio::Connections::StandIn.install!(Studio.connection(:files))
12
+ # Studio::Connections::StandIn.install!(Studio.connection(:tenant),
13
+ # callback_params: { tenant: "00000000-0000-0000-0000-000000000000", admin_consent: "True" })
14
+ #
15
+ # The sign-in page comes straight back to the callback with the stand-in's
16
+ # code (and any callback_params). The token and revoke endpoints are stood
17
+ # in at the HTTP layer (Provider#http), so the real exchange, refresh and
18
+ # rotation run: like a rotating provider, every grant answers a new refresh
19
+ # token and only the LAST one issued for a token URL is honoured, so a
20
+ # refresh that failed to store its new pair shows up as Revoked on the next
21
+ # read. Access tokens live `access_lifetime` seconds. The memory is this
22
+ # process's own.
23
+ module StandIn
24
+ CODE = "studio-connection-stand-in-code"
25
+
26
+ class SignIn
27
+ def initialize(callback_params: {})
28
+ @callback_params = callback_params.to_h
29
+ end
30
+
31
+ def authorize_url(redirect_uri:, state:, account: nil)
32
+ query = { code: CODE }.merge(@callback_params).merge(state:)
33
+ "#{redirect_uri}?#{URI.encode_www_form(query)}"
34
+ end
35
+ end
36
+
37
+ # The token and revoke endpoints: (url, form, headers) -> [status, body].
38
+ class Tokens
39
+ attr_reader :requests
40
+
41
+ def initialize(access_lifetime: 3600)
42
+ @access_lifetime = access_lifetime
43
+ @live = {}
44
+ @requests = []
45
+ @lock = Mutex.new
46
+ end
47
+
48
+ def call(url, form, headers)
49
+ @lock.synchronize do
50
+ @requests << { url:, form:, headers: }
51
+ next [200, ""] if form.key?(:token)
52
+
53
+ case form[:grant_type]
54
+ when "authorization_code"
55
+ form[:code] == CODE ? issue(url) : refuse
56
+ when "refresh_token"
57
+ @live[url] && form[:refresh_token] == @live[url] ? issue(url) : refuse
58
+ when "client_credentials"
59
+ [200, { token_type: "Bearer", expires_in: @access_lifetime, access_token: "stand-in-access-#{SecureRandom.hex(8)}" }.to_json]
60
+ else [400, { error: "unsupported_grant_type" }.to_json]
61
+ end
62
+ end
63
+ end
64
+
65
+ private
66
+
67
+ def refuse = [400, { error: "invalid_grant", error_description: "the stand-in did not issue that" }.to_json]
68
+
69
+ def issue(url)
70
+ @live[url] = "stand-in-refresh-#{SecureRandom.hex(8)}"
71
+ [200, { access_token: "stand-in-access-#{SecureRandom.hex(8)}", refresh_token: @live[url],
72
+ expires_in: @access_lifetime, token_type: "bearer" }.to_json]
73
+ end
74
+ end
75
+
76
+ def self.install!(provider, callback_params: {}, access_lifetime: 3600)
77
+ provider.sign_in_stand_in = SignIn.new(callback_params:)
78
+ provider.http = Tokens.new(access_lifetime:)
79
+ provider
80
+ end
81
+
82
+ def self.uninstall!(provider)
83
+ provider.sign_in_stand_in = nil
84
+ provider.http = nil
85
+ provider
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,483 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+ require "json"
7
+ require "base64"
8
+ require "set"
9
+
10
+ module Studio
11
+ # CONNECTIONS: the generic tooling a host app uses to connect a third-party
12
+ # account over OAuth 2.0 (docs/CONNECTIONS.md). The engine knows no provider.
13
+ # A host declares each one in an initializer, and the engine gives it:
14
+ #
15
+ # * Studio::Connection, one table (studio_connections) holding one row per
16
+ # provider and account, with the tokens encrypted (bin/rails g studio:connections);
17
+ # * the OAuth plumbing on the Provider below: state, the authorize URL, the
18
+ # code exchange, the refresh policy, the revoke, and two test seams;
19
+ # * Studio::ConnectionFlow, the connect, callback and disconnect actions,
20
+ # and Studio.draw_connection_routes, which draws them;
21
+ # * the log filter for the keys a provider names (LOG_FILTER).
22
+ #
23
+ # Studio.define_connection :files,
24
+ # label: "Acme Files",
25
+ # env: { client_id: "ACME_CLIENT_ID", client_secret: "ACME_CLIENT_SECRET" },
26
+ # authorize_url: ->(account) { "https://#{account}.files.example/oauth/authorize" },
27
+ # token_url: ->(account) { "https://#{account}.files.example/oauth/token" },
28
+ # scopes: %w[files.read],
29
+ # refresh: :cached, refresh_margin: 1.day,
30
+ # account: :connect, account_param: "domain", account_format: /\A[a-z0-9-]{1,63}\z/
31
+ #
32
+ # Provider specifics (endpoints, scopes, quirks, readers, the admin page's
33
+ # live read) belong to the host. Nothing here is named after a vendor.
34
+ module Connections
35
+ # What reaching a provider can raise below HTTP: TLS, refused, timed out, DNS.
36
+ NETWORK_ERRORS = [OpenSSL::SSL::SSLError, SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout].freeze
37
+
38
+ ENCRYPTION_ENV = %w[ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY
39
+ ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT].freeze
40
+
41
+ class Error < StandardError; end
42
+ # The provider's client id or secret is not set on this server.
43
+ class NotConfigured < Error; end
44
+ # The provider no longer honours the stored grant: revoked, expired, superseded.
45
+ class Revoked < Error; end
46
+ # The provider is throttling this app or this token.
47
+ class RateLimited < Error; end
48
+
49
+ # Where the browser leg starts, per grant.
50
+ GRANTS = %i[authorization_code client_credentials].freeze
51
+ # How an access token is obtained after the browser leg:
52
+ # :rotating refresh on every call, under the row's lock, storing the
53
+ # answered refresh token before the access token is used; no
54
+ # access token is stored
55
+ # :cached keep the access token, encrypted, and refresh it under the
56
+ # row's lock only within refresh_margin of its expiry (or after
57
+ # a 401, named by `stale:`), storing the new pair before use
58
+ # :memory the client-credentials grant: no refresh token exists, and the
59
+ # access token lives in this process's memory only
60
+ REFRESH_POLICIES = %i[rotating cached memory].freeze
61
+ # Where the account a row is keyed by comes from:
62
+ # :connect the admin names it before Connect (a form param); it is kept
63
+ # in the session, and the callback never reads it from its query
64
+ # :callback the provider names it on the callback (a query param)
65
+ # :described the host's describe hook names it after the exchange
66
+ ACCOUNT_SOURCES = %i[connect callback described].freeze
67
+ CLIENT_AUTH = %i[form basic secret_only].freeze
68
+
69
+ # An account that fails the provider's format: it never reaches a URL or a row.
70
+ class InvalidAccount < ArgumentError; end
71
+
72
+ # One provider's drawn routes: where they live, the controller serving
73
+ # them, the route-name prefix, and the return_to allowlist (first = default).
74
+ Route = Struct.new(:provider, :path, :as, :controller, :return_paths, keyword_init: true)
75
+
76
+ class << self
77
+ def define(key, **options)
78
+ provider = Provider.new(key, **options)
79
+ registry_lock.synchronize do
80
+ @filter_keys = nil
81
+ registry[provider.key] = provider
82
+ end
83
+ end
84
+
85
+ def fetch(key)
86
+ registry_lock.synchronize { registry[key.to_s] } or raise ArgumentError, "no connection provider is defined as #{key.to_s.inspect}"
87
+ end
88
+
89
+ def defined?(key) = registry_lock.synchronize { registry.key?(key.to_s) }
90
+ def all = registry_lock.synchronize { registry.values }
91
+
92
+ # Forgets every provider and route. Tests only.
93
+ def reset!
94
+ registry_lock.synchronize do
95
+ registry.clear
96
+ routes.clear
97
+ @filter_keys = @controllers = nil
98
+ end
99
+ end
100
+
101
+ # The routes Studio.draw_connection_routes drew, by provider key.
102
+ def routes = (@routes ||= {})
103
+ def route(key) = registry_lock.synchronize { routes[key.to_s] }
104
+
105
+ def record_route(route)
106
+ registry_lock.synchronize do
107
+ @controllers = nil
108
+ routes[route.provider] = route
109
+ end
110
+ end
111
+
112
+ # The controllers that serve a callback, as params["controller"] names them.
113
+ # Memoized: the log filter asks on every logged parameter.
114
+ def controllers = @controllers || registry_lock.synchronize { @controllers ||= routes.values.map(&:controller).to_set.freeze }
115
+
116
+ # Every exact key a provider asked to keep out of the logs.
117
+ def filter_keys = @filter_keys || registry_lock.synchronize { @filter_keys ||= registry.values.flat_map(&:filter_keys).to_set.freeze }
118
+
119
+ # Can this app store a connection: are its Active Record encryption keys set?
120
+ def encryption_ready?
121
+ return false unless defined?(::ActiveRecord::Encryption)
122
+
123
+ config = ::ActiveRecord::Encryption.config
124
+ config.has_primary_key?.present? && config.has_key_derivation_salt?.present?
125
+ end
126
+
127
+ # True on a production server.
128
+ def production?
129
+ defined?(::Rails) && ::Rails.respond_to?(:env) && ::Rails.env.production?
130
+ end
131
+
132
+ # The test seams are allowed only in development and test (or with no
133
+ # Rails at all): a staging or QA environment refuses them as production does.
134
+ def seams_allowed?
135
+ return true unless defined?(::Rails) && ::Rails.respond_to?(:env)
136
+
137
+ ::Rails.env.development? || ::Rails.env.test?
138
+ end
139
+
140
+ private
141
+
142
+ def registry = (@registry ||= {})
143
+ def registry_lock = (@registry_lock ||= Monitor.new)
144
+ end
145
+
146
+ # THE LOG FILTER, which the engine appends to config.filter_parameters.
147
+ #
148
+ # Rails 8.1 filters the "Started GET" line's URL one query pair at a time,
149
+ # as a one-key hash with no controller to scope by
150
+ # (ActionDispatch::Http::FilterParameters#filtered_query_string), so a
151
+ # controller-scoped filter leaves a callback's account id in that line. A
152
+ # provider's filter_keys are therefore matched by EXACT key wherever they
153
+ # appear, String values only (a nested Hash under the same name is spared).
154
+ #
155
+ # The auth code is masked in the Parameters line of the connection
156
+ # controllers only: a bare `code` filter would mask every other `code` param
157
+ # in the app. It still rides the Started GET URL, where it is already spent.
158
+ LOG_FILTER = lambda do |key, value, params = nil|
159
+ next unless value.is_a?(String)
160
+
161
+ name = key.to_s
162
+ if Studio::Connections.filter_keys.include?(name)
163
+ value.replace("[FILTERED]")
164
+ elsif name == "code" && params.is_a?(Hash) && Studio::Connections.controllers.include?(params["controller"].to_s)
165
+ value.replace("[FILTERED]")
166
+ end
167
+ end
168
+
169
+ # One provider, as a host declared it. Every option is checked here, at
170
+ # boot, so a typo fails the host's boot instead of a sign-in.
171
+ class Provider
172
+ Token = Struct.new(:value, :expires_at)
173
+
174
+ attr_reader :key, :label, :env, :grant, :refresh, :refresh_margin, :scopes, :client_auth, :revoke_auth,
175
+ :revoke_format, :account_source, :account_param, :account_format, :private_account,
176
+ :authorize_params, :exchange_params, :rotation, :refresh_expires_in_key, :declined_errors,
177
+ :refusal_hint, :revoked_errors, :revoked_pattern, :rate_limited_statuses, :filter_keys,
178
+ :revoke_note, :callback_check, :describe
179
+
180
+ # Stand-in for the provider's token and revoke endpoints:
181
+ # (url, form, headers) -> [status, body]. nil means the provider itself.
182
+ # Tests, the e2e lane and a local demo only; refused outside development and test.
183
+ attr_reader :http
184
+
185
+ # Stand-in for the provider's sign-in page (authorize_url only), for the
186
+ # e2e lane and a local demo: anything answering
187
+ # authorize_url(redirect_uri:, state:, account:). Refused outside development and test.
188
+ # The code exchange and the refresh still run through .http.
189
+ attr_reader :sign_in_stand_in
190
+
191
+ def initialize(key, label:, env:, authorize_url:, token_url:, revoke_url: nil, grant: :authorization_code,
192
+ refresh: nil, refresh_margin: 5.minutes, scopes: [], client_auth: :form, revoke_auth: nil,
193
+ revoke_format: :form, account: :callback, account_param: nil, account_format: nil,
194
+ normalize_account: nil, private_account: false, authorize_params: {}, exchange_params: {},
195
+ rotation: nil, refresh_expires_in_key: nil, declined_errors: %w[access_denied],
196
+ refusal_hint: "Check the app's redirect URI, then start again.", revoked_errors: %w[invalid_grant],
197
+ revoked_pattern: nil, rate_limited_statuses: [429], filter_keys: [], revoke_note: nil,
198
+ callback_check: nil, describe: nil)
199
+ @key = key.to_s
200
+ 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
+
202
+ @label = label.to_s
203
+ @env = env.to_h.transform_keys(&:to_sym)
204
+ raise ArgumentError, "#{@key}: env names client_id and client_secret" unless @env.keys.sort == %i[client_id client_secret] && @env.values.all?(String)
205
+
206
+ @grant = choose(grant, GRANTS, "grant")
207
+ @refresh = choose(refresh || (@grant == :client_credentials ? :memory : :rotating), REFRESH_POLICIES, "refresh")
208
+ if (@grant == :client_credentials) != (@refresh == :memory)
209
+ raise ArgumentError, "#{@key}: the client-credentials grant, and only it, keeps its token in memory (refresh: :memory)"
210
+ end
211
+
212
+ @authorize_url = authorize_url
213
+ @token_url = token_url
214
+ @revoke_url = revoke_url
215
+ @refresh_margin = refresh_margin
216
+ @scopes = Array(scopes).map(&:to_s)
217
+ @client_auth = choose(client_auth, CLIENT_AUTH - [:secret_only], "client_auth")
218
+ @revoke_auth = choose(revoke_auth || @client_auth, CLIENT_AUTH, "revoke_auth")
219
+ @revoke_format = choose(revoke_format, %i[form json], "revoke_format")
220
+ @account_source = choose(account, ACCOUNT_SOURCES, "account")
221
+ @account_param = account_param&.to_s
222
+ @account_format = account_format
223
+ if %i[connect callback].include?(@account_source) && !(@account_param && @account_format.is_a?(Regexp))
224
+ raise ArgumentError, "#{@key}: an account from the #{@account_source} needs account_param and an account_format Regexp"
225
+ end
226
+ @normalize_account = normalize_account || ->(value) { value.to_s.strip }
227
+ @private_account = private_account ? true : false
228
+ @authorize_params = authorize_params.to_h
229
+ @exchange_params = exchange_params.to_h
230
+ @rotation = choose(rotation || (@refresh == :rotating ? :required : :optional), %i[required optional], "rotation")
231
+ @refresh_expires_in_key = refresh_expires_in_key&.to_s
232
+ @declined_errors = Array(declined_errors).map(&:to_s)
233
+ @refusal_hint = refusal_hint.to_s
234
+ @revoked_errors = Array(revoked_errors).map(&:to_s)
235
+ @revoked_pattern = revoked_pattern
236
+ @rate_limited_statuses = Array(rate_limited_statuses).map(&:to_i)
237
+ @filter_keys = Array(filter_keys).map(&:to_s)
238
+ # A private account's callback param is filtered whether or not the host listed it.
239
+ @filter_keys |= [@account_param] if @private_account && @account_source == :callback
240
+ @revoke_note = revoke_note || "Remove this app's access in #{@label} to revoke it there."
241
+ @callback_check = callback_check
242
+ @describe = describe
243
+ @cache = {}
244
+ @cache_lock = Mutex.new
245
+ end
246
+
247
+ def http=(callable)
248
+ refuse_seam_outside_dev_and_test!("http") unless callable.nil?
249
+ @http = callable
250
+ end
251
+
252
+ def sign_in_stand_in=(stand_in)
253
+ refuse_seam_outside_dev_and_test!("sign_in_stand_in") unless stand_in.nil?
254
+ @sign_in_stand_in = stand_in
255
+ end
256
+
257
+ def client_id = ENV[env[:client_id]].to_s
258
+ def client_secret = ENV[env[:client_secret]].to_s
259
+ def env_names = env.values
260
+
261
+ # The client id and secret are set on this server.
262
+ def configured? = env_names.all? { |name| ENV[name].to_s.strip != "" }
263
+
264
+ # Can a Connect start on this server: the client is set, or the stand-in is.
265
+ def connectable? = configured? || !sign_in_stand_in.nil?
266
+
267
+ def revocable? = !@revoke_url.nil?
268
+
269
+ # The account as a row keys it, or nil when it is not one: normalized,
270
+ # then held to account_format (always, when one is given). A strict
271
+ # format is what keeps an account named in a form out of a URL's host.
272
+ def normalize_account(value)
273
+ normalized = @normalize_account.call(value)
274
+ return nil if normalized.nil? || normalized.to_s.empty?
275
+
276
+ normalized = normalized.to_s
277
+ return nil if account_format && !account_format.match?(normalized)
278
+
279
+ normalized
280
+ end
281
+
282
+ # What a row is unique by: the account itself, or a keyed digest of it
283
+ # when the account is private (it is then stored only encrypted).
284
+ def account_key_for(account)
285
+ return account unless private_account
286
+
287
+ secret = defined?(::Rails) && ::Rails.application ? ::Rails.application.secret_key_base : raise(Error, "no secret_key_base to key a private account by")
288
+ OpenSSL::HMAC.hexdigest("SHA256", secret, "studio-connection:#{key}:#{account}")
289
+ end
290
+
291
+ # An endpoint's URL: the static String, or the callable's answer for a
292
+ # checked account (a per-account host). Raises InvalidAccount for an
293
+ # account that fails account_format, so it never reaches a URL.
294
+ def url_for(option, account)
295
+ value = { authorize: @authorize_url, token: @token_url, revoke: @revoke_url }.fetch(option)
296
+ return nil if value.nil?
297
+ return value.to_s unless value.respond_to?(:call)
298
+
299
+ checked = normalize_account(account) or raise InvalidAccount, "not a #{label} account"
300
+ value.call(checked).to_s
301
+ end
302
+
303
+ # Where the browser goes to sign in (a code grant) or approve the app (a
304
+ # client-credentials grant's admin consent).
305
+ def authorize_url(redirect_uri:, state:, account: nil)
306
+ return sign_in_stand_in.authorize_url(redirect_uri:, state:, account:) if sign_in_stand_in
307
+
308
+ ensure_configured!
309
+ params = { client_id:, redirect_uri:, state: }
310
+ if grant == :authorization_code
311
+ params[:response_type] = "code"
312
+ params[:scope] = scopes.join(" ") if scopes.any?
313
+ end
314
+ url = url_for(:authorize, account)
315
+ "#{url}#{url.include?('?') ? '&' : '?'}#{URI.encode_www_form(params.merge(authorize_params))}"
316
+ end
317
+
318
+ # The token endpoint's JSON for a sign-in's code.
319
+ def exchange_code(code:, redirect_uri:, account: nil)
320
+ token_request(account, { grant_type: "authorization_code", code:, redirect_uri: }.merge(exchange_params))
321
+ end
322
+
323
+ # An access token for `connection` (a Studio::Connection; for :memory,
324
+ # also a bare account id), by this provider's refresh policy. Raises
325
+ # Revoked when the provider no longer honours the grant.
326
+ def access_token(connection, stale: nil, now: Time.current)
327
+ case refresh
328
+ when :rotating then rotating_access_token(connection, now:)
329
+ when :cached then cached_access_token(connection, stale:, now:)
330
+ when :memory then memory_access_token(connection.respond_to?(:account_id) ? connection.account_id : connection, now:)
331
+ end
332
+ end
333
+
334
+ # Revokes the connection's grant at the provider. True when it took it;
335
+ # nil when this provider has no revoke endpoint; raises Error otherwise.
336
+ def revoke(connection)
337
+ return nil unless revocable?
338
+
339
+ token = connection.refresh_token.presence || connection.access_token
340
+ raise Error, "this connection holds no token to revoke" if token.to_s.empty?
341
+
342
+ form = { token: }
343
+ post(url_for(:revoke, connection.account_id), form, auth: revoke_auth, format: revoke_format, allow_empty: true)
344
+ true
345
+ end
346
+
347
+ # Drops the in-memory token of one account, or every account's (:memory).
348
+ def forget!(account = nil)
349
+ @cache_lock.synchronize { account ? @cache.delete(account.to_s.downcase) : @cache.clear }
350
+ end
351
+
352
+ # How many accounts have a token cached in this process (:memory).
353
+ def cached_count = @cache_lock.synchronize { @cache.size }
354
+
355
+ # When a grant's token stops working, from a seconds field; nil when the
356
+ # provider gave no positive lifetime.
357
+ def self.expiry(grant, field, now)
358
+ return nil if field.nil?
359
+
360
+ seconds = Integer(grant[field].to_s, exception: false)
361
+ seconds&.positive? ? now + seconds : nil
362
+ end
363
+
364
+ private
365
+
366
+ def choose(value, allowed, name)
367
+ value = value.to_sym
368
+ return value if allowed.include?(value)
369
+
370
+ raise ArgumentError, "#{@key}: #{name} is one of #{allowed.map(&:inspect).join(', ')}, not #{value.inspect}"
371
+ end
372
+
373
+ def refuse_seam_outside_dev_and_test!(name)
374
+ raise Error, "#{label}: the #{name} stand-in is for tests, the e2e lane and a local demo (development and test only)" unless Connections.seams_allowed?
375
+ end
376
+
377
+ def ensure_configured!
378
+ raise NotConfigured, "#{env_names.join(' and ')} are not set on this server" unless configured? || http
379
+ end
380
+
381
+ def rotating_access_token(connection, now:)
382
+ answer = connection.with_lock do
383
+ raise Revoked, "#{label}: this connection holds no refresh token; connect again" if connection.refresh_token.blank?
384
+
385
+ grant = token_request(connection.account_id, { grant_type: "refresh_token", refresh_token: connection.refresh_token })
386
+ connection.rotate!(grant, now:)
387
+ grant
388
+ end
389
+ # After the lock commits: a raise inside it would roll back the token the provider already rotated.
390
+ answer["access_token"].presence or raise Error, "#{label} answered a refresh with no access token"
391
+ end
392
+
393
+ def cached_access_token(connection, stale:, now:)
394
+ connection.with_lock do
395
+ current = connection.access_token
396
+ next current if stale.present? && current != stale
397
+ next current if stale.blank? && connection.access_fresh?(now)
398
+ raise Revoked, "#{label}: this connection holds no refresh token; connect again" if connection.refresh_token.blank?
399
+
400
+ grant = token_request(connection.account_id, { grant_type: "refresh_token", refresh_token: connection.refresh_token })
401
+ raise Error, "#{label} answered a refresh with no access token" if grant["access_token"].blank?
402
+
403
+ connection.rotate!(grant, now:)
404
+ grant["access_token"]
405
+ end
406
+ end
407
+
408
+ def memory_access_token(account, now:)
409
+ account = normalize_account(account) or raise InvalidAccount, "not a #{label} account"
410
+ cache_key = account.downcase
411
+ cached = @cache_lock.synchronize { @cache[cache_key] }
412
+ return cached.value if cached && cached.expires_at > now
413
+
414
+ form = { grant_type: "client_credentials" }
415
+ form[:scope] = scopes.join(" ") if scopes.any?
416
+ answer = token_request(account, form)
417
+ value = answer["access_token"].presence or raise Error, "#{label} answered a token request with no access token"
418
+ lifetime = answer["expires_in"].to_i
419
+ @cache_lock.synchronize { @cache[cache_key] = Token.new(value, now + lifetime - refresh_margin) }
420
+ value
421
+ end
422
+
423
+ def token_request(account, form)
424
+ post(url_for(:token, account), form, auth: client_auth, format: :form)
425
+ end
426
+
427
+ def post(url, form, auth:, format:, allow_empty: false)
428
+ ensure_configured!
429
+ headers = { "Accept" => "application/json",
430
+ "Content-Type" => format == :json ? "application/json" : "application/x-www-form-urlencoded" }
431
+ case auth
432
+ when :form then form = form.merge(client_id:, client_secret:)
433
+ when :secret_only then form = form.merge(client_secret:)
434
+ when :basic then headers["Authorization"] = "Basic #{Base64.strict_encode64("#{client_id}:#{client_secret}")}"
435
+ end
436
+ status, body = call(url, form, headers)
437
+ json = parse(body)
438
+ # A revoke (allow_empty) is confirmed by any 2xx, a 204 included; a token answer must be a 200 with a body.
439
+ return json if allow_empty ? (200..299).cover?(status) : (status == 200 && json.any?)
440
+
441
+ raise_for(status, json)
442
+ end
443
+
444
+ def raise_for(status, json)
445
+ detail = json["error_description"].to_s.lines.first.to_s.strip
446
+ detail = (json["error"] || json["message"] || json["errorMessage"]).to_s if detail.empty?
447
+ detail = "no detail" if detail.empty?
448
+ raise RateLimited, "#{label} is throttling this app (#{status}); try again in a few minutes" if rate_limited_statuses.include?(status)
449
+ raise Revoked, "#{label} no longer accepts this connection (#{detail}); connect again" if revoked?(status, json, detail)
450
+
451
+ raise Error, "#{label} answered #{status}: #{detail}"
452
+ end
453
+
454
+ def revoked?(status, json, detail)
455
+ return false unless [400, 401, 403].include?(status)
456
+
457
+ revoked_errors.include?(json["error"].to_s) || (revoked_pattern ? revoked_pattern.match?(detail) : false)
458
+ end
459
+
460
+ def parse(body)
461
+ json = JSON.parse(body.to_s)
462
+ json.is_a?(Hash) ? json : {}
463
+ rescue JSON::ParserError
464
+ {}
465
+ end
466
+
467
+ def call(url, form, headers)
468
+ return http.call(url, form, headers) if http
469
+
470
+ uri = URI(url)
471
+ raise Error, "#{label}: a token endpoint must be https" unless uri.scheme == "https"
472
+
473
+ request = Net::HTTP::Post.new(uri)
474
+ headers.each { |name, value| request[name] = value }
475
+ request.body = headers["Content-Type"] == "application/json" ? JSON.generate(form) : URI.encode_www_form(form)
476
+ 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]
478
+ rescue *NETWORK_ERRORS => e
479
+ raise Error, "#{label} could not be reached: #{e.class}"
480
+ end
481
+ end
482
+ end
483
+ end
data/lib/studio/engine.rb CHANGED
@@ -315,6 +315,14 @@ module Studio
315
315
  app.config.filter_parameters += [/(\A|\.)voice\.(embeddings|embedding|audio)\z/, /\Avoice_embedding\z/]
316
316
  end
317
317
 
318
+ # The connections' log filter (Studio::Connections::LOG_FILTER): each
319
+ # provider's filter_keys by exact key, and the auth code on the connection
320
+ # controllers. One lambda that reads the registry when it runs, so a
321
+ # provider declared in a host initializer, after this, is covered.
322
+ initializer "studio.connections.filter_parameters" do |app|
323
+ app.config.filter_parameters += [Studio::Connections::LOG_FILTER]
324
+ end
325
+
318
326
  initializer "studio.footer_only_eager_load" do
319
327
  next if Studio.active_record?
320
328
 
@@ -1,3 +1,3 @@
1
1
  module Studio
2
- VERSION = "0.136.0"
2
+ VERSION = "0.137.0"
3
3
  end
data/lib/studio.rb CHANGED
@@ -75,6 +75,8 @@ require "studio/email_smoke"
75
75
  require "studio/mail_transport"
76
76
  require "studio/redis"
77
77
  require "studio/cable"
78
+ require "studio/connections"
79
+ require "studio/connections/stand_in"
78
80
  require "studio/survey"
79
81
  require "studio/survey/breakdown"
80
82
  require "studio/survey/export"
@@ -1199,6 +1201,64 @@ module Studio
1199
1201
  # logged and swallowed — the respondent still lands on the thank-you screen.
1200
1202
  mattr_accessor :on_survey_completed, default: ->(_response) {}
1201
1203
 
1204
+ # ---- Connections (docs/CONNECTIONS.md) ------------------------------------
1205
+ #
1206
+ # The generic OAuth 2.0 connection tooling. The engine names no provider: a
1207
+ # host declares each in an initializer and draws its routes.
1208
+ #
1209
+ # Studio.define_connection :files, label: "Acme Files", env: {...}, ...
1210
+ # # config/routes.rb
1211
+ # Studio.draw_connection_routes(self, :files, path: "admin/files", controller: "admin/files")
1212
+ #
1213
+ # Every option is documented on Studio::Connections::Provider#initialize.
1214
+ def self.define_connection(key, **options)
1215
+ Connections.define(key, **options)
1216
+ end
1217
+
1218
+ def self.connection(key)
1219
+ Connections.fetch(key)
1220
+ end
1221
+
1222
+ # Who may connect, call back and disconnect: a method name on the connection
1223
+ # controller (the host's ApplicationController, through Studio::ErrorHandling,
1224
+ # answers :require_admin), or a callable taking the controller.
1225
+ mattr_accessor :connection_admin_guard, default: :require_admin
1226
+
1227
+ # Draws one provider's connect, callback and disconnect into the host's
1228
+ # routes, and records them for the log filter and the callback URL:
1229
+ #
1230
+ # POST /<path>/connect <as>_connect (also GET when the provider takes no account at Connect)
1231
+ # GET /<path>/callback <as>_callback (the redirect URI to register)
1232
+ # DELETE /<path>/connections/:id <as>_disconnect
1233
+ # GET /<path> <as> (only with show: true)
1234
+ #
1235
+ # controller: the host's own controller including Studio::ConnectionFlow
1236
+ # (default: the engine's Studio::ConnectionsController). show: draws the
1237
+ # page itself at <path> (default: true when the host names its controller).
1238
+ # return_to: the allowlist return_to may name; its first path is the default
1239
+ # (default: ["/<path>"]).
1240
+ def self.draw_connection_routes(router, key, path: "admin/#{key}", controller: nil, as: nil, return_to: nil, show: nil)
1241
+ provider = Connections.fetch(key)
1242
+ path = path.to_s.delete_prefix("/").delete_suffix("/")
1243
+ controller = (controller || "studio/connections").to_s.delete_prefix("/")
1244
+ as = (as || path.tr("/-", "__")).to_s
1245
+ show = controller != "studio/connections" if show.nil?
1246
+ return_paths = Array(return_to || ["/#{path}"]).map(&:to_s)
1247
+ Connections.record_route(Connections::Route.new(provider: provider.key, path:, as:, controller:, return_paths:))
1248
+
1249
+ defaults = { studio_connection: provider.key }
1250
+ router.instance_exec do
1251
+ get "#{path}", to: "#{controller}#show", as: as, defaults: defaults if show
1252
+ # POST-only when the admin names the account at Connect: a GET would skip
1253
+ # the CSRF check, so a link carrying an attacker's account could start a
1254
+ # connection to it in a signed-in admin's session.
1255
+ connect_via = provider.account_source == :connect ? %i[post] : %i[get post]
1256
+ match "#{path}/connect", to: "#{controller}#connect", as: "#{as}_connect", via: connect_via, defaults: defaults
1257
+ get "#{path}/callback", to: "#{controller}#callback", as: "#{as}_callback", defaults: defaults
1258
+ delete "#{path}/connections/:id", to: "#{controller}#disconnect", as: "#{as}_disconnect", defaults: defaults
1259
+ end
1260
+ end
1261
+
1202
1262
  # Define a survey in app code. See Studio::Survey for the DSL.
1203
1263
  def self.define_survey(slug, &block)
1204
1264
  Survey.define(slug, &block)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: studio-engine
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.136.0
4
+ version: 0.137.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Alex McRitchie
@@ -444,6 +444,7 @@ files:
444
444
  - app/controllers/concerns/solana/session_auth.rb
445
445
  - app/controllers/concerns/studio/admin_models.rb
446
446
  - app/controllers/concerns/studio/board/reorderable.rb
447
+ - app/controllers/concerns/studio/connection_flow.rb
447
448
  - app/controllers/concerns/studio/error_handling.rb
448
449
  - app/controllers/concerns/studio/geo_detection.rb
449
450
  - app/controllers/concerns/studio/link_consumption.rb
@@ -462,6 +463,7 @@ files:
462
463
  - app/controllers/studio/agent_chats_controller.rb
463
464
  - app/controllers/studio/bookings_controller.rb
464
465
  - app/controllers/studio/component_previews_controller.rb
466
+ - app/controllers/studio/connections_controller.rb
465
467
  - app/controllers/studio/emails_controller.rb
466
468
  - app/controllers/studio/geo_settings_controller.rb
467
469
  - app/controllers/studio/google_setup_requests_controller.rb
@@ -600,6 +602,7 @@ files:
600
602
  - app/models/error_log.rb
601
603
  - app/models/image_cache.rb
602
604
  - app/models/session_context.rb
605
+ - app/models/studio/connection.rb
603
606
  - app/models/studio/email_delivery.rb
604
607
  - app/models/studio/email_setting.rb
605
608
  - app/models/studio/enumeral.rb
@@ -878,9 +881,11 @@ files:
878
881
  - db/migrate/20261029120000_add_voice_profile_to_users.rb
879
882
  - db/migrate/20261103120000_create_studio_user_sessions.rb
880
883
  - db/migrate/20261108120000_add_device_revocation_to_studio_user_sessions.rb
884
+ - db/migrate/20261108130000_create_studio_connections.rb
881
885
  - docs/BOOKING.md
882
886
  - docs/SITE_FOOTER.md
883
887
  - lib/active_storage/service/studio_trash_s3_service.rb
888
+ - lib/generators/studio/connections/connections_generator.rb
884
889
  - lib/generators/studio/site_identity/site_identity_generator.rb
885
890
  - lib/studio-engine.rb
886
891
  - lib/studio.rb
@@ -890,6 +895,8 @@ files:
890
895
  - lib/studio/cable.rb
891
896
  - lib/studio/color_scale.rb
892
897
  - lib/studio/component_gallery.rb
898
+ - lib/studio/connections.rb
899
+ - lib/studio/connections/stand_in.rb
893
900
  - lib/studio/crumbs.rb
894
901
  - lib/studio/email.rb
895
902
  - lib/studio/email_image_generator.rb