studio-engine 0.136.0 → 0.138.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.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +29 -0
  3. data/README.md +29 -0
  4. data/app/assets/tailwind/studio_engine/engine.css +228 -0
  5. data/app/controllers/concerns/studio/connection_flow.rb +215 -0
  6. data/app/controllers/sessions_controller.rb +12 -3
  7. data/app/controllers/studio/connections_controller.rb +13 -0
  8. data/app/controllers/studio/integrations_controller.rb +43 -0
  9. data/app/controllers/studio/local_reviews_controller.rb +12 -0
  10. data/app/javascript/studio/carousel.js +66 -0
  11. data/app/javascript/studio/controllers/carousel_controller.js +203 -1
  12. data/app/models/concerns/studio/account.rb +143 -0
  13. data/app/models/concerns/studio/omniauth_user.rb +9 -17
  14. data/app/models/error_log.rb +14 -5
  15. data/app/models/studio/connection.rb +137 -0
  16. data/app/views/studio/_carousel.html.erb +58 -14
  17. data/app/views/studio/integrations/_card.html.erb +50 -0
  18. data/app/views/studio/integrations/index.html.erb +22 -0
  19. data/app/views/studio/integrations/show.html.erb +24 -0
  20. data/app/views/style/_tricks.html.erb +15 -0
  21. data/config/studio_tricks.yml +7 -0
  22. data/db/migrate/20261006120001_ensure_error_logs_table.rb +3 -1
  23. data/db/migrate/20261006120002_ensure_theme_settings_table.rb +3 -2
  24. data/db/migrate/20261108130000_create_studio_connections.rb +35 -0
  25. data/db/migrate/20261108160000_require_slugs_on_engine_tables.rb +119 -0
  26. data/db/migrate/20261108160001_add_engine_state_checks.rb +94 -0
  27. data/db/migrate/20261108170000_add_users_role_known_check.rb +69 -0
  28. data/lib/generators/studio/connections/connections_generator.rb +103 -0
  29. data/lib/studio/connections/stand_in.rb +89 -0
  30. data/lib/studio/connections.rb +524 -0
  31. data/lib/studio/engine.rb +8 -0
  32. data/lib/studio/integrations/egnyte.rb +69 -0
  33. data/lib/studio/integrations/microsoft_365.rb +63 -0
  34. data/lib/studio/integrations/quickbooks.rb +86 -0
  35. data/lib/studio/integrations.rb +265 -0
  36. data/lib/studio/node_tooling/README.md +9 -1
  37. data/lib/studio/node_tooling/e2e_helpers.js +93 -1
  38. data/lib/studio/node_tooling/playwright_base.js +51 -4
  39. data/lib/studio/roles.rb +17 -0
  40. data/lib/studio/version.rb +1 -1
  41. data/lib/studio.rb +118 -0
  42. metadata +22 -2
@@ -0,0 +1,94 @@
1
+ # The engine's two state columns take the hub's state standard: a CHECK named
2
+ # `<table>_<column>_known` holding the list the model validates against, so a
3
+ # write that skips validations (update_columns, update_all, insert_all, raw SQL)
4
+ # is refused by the database (database audit 2026-11-07, finding 6).
5
+ #
6
+ # studio_links.kind Studio::LinkToken::KINDS (Studio::Link validates it)
7
+ # studio_knowledge_docs.status Studio::KnowledgeDoc::STATUSES
8
+ #
9
+ # The lists below are this migration's own frozen copy. A new value needs a new
10
+ # migration: test/integration/engine_state_checks_test.rb fails while a model's
11
+ # list and this copy differ.
12
+ #
13
+ # A host without the table is skipped, and a constraint already there is left
14
+ # alone, so a second run changes nothing. Both columns are NOT NULL already.
15
+ #
16
+ # A row outside its list stops the migration before any change, with the table,
17
+ # the column and the stray values in the message: the constraint is validated,
18
+ # so it cannot go on over such a row. Production on 2026-11-08 held none (every
19
+ # app with a database, read-only counts): studio_links holds magic_link and
20
+ # referral, studio_knowledge_docs holds filed and superseded (industries alone).
21
+ # The validating scan is short (the largest table is 366 rows). On Postgres the
22
+ # ALTER waits at most LOCK_TIMEOUT for its lock; a migrate that cannot get it
23
+ # fails whole and runs again on the next release.
24
+ class AddEngineStateChecks < ActiveRecord::Migration[7.2]
25
+ LOCK_TIMEOUT = "10s"
26
+
27
+ CHECKS = {
28
+ "studio_links.kind" => %w[magic_link referral],
29
+ "studio_knowledge_docs.status" => %w[inbox filed superseded]
30
+ }.freeze
31
+
32
+ # The constraint's name: `<table>_<column>_known`, as the hub names its own.
33
+ def self.constraint_name(key) = key.tr(".", "_") + "_known"
34
+
35
+ def up
36
+ set_lock_timeout
37
+ CHECKS.each do |key, values|
38
+ table, column = key.split(".")
39
+ next unless table_exists?(table)
40
+ next if check_constraint_exists?(table, name: self.class.constraint_name(key))
41
+
42
+ refuse_strays!(table, column, values)
43
+ add_check_constraint table, expression(column, values), name: self.class.constraint_name(key)
44
+ end
45
+ end
46
+
47
+ def down
48
+ CHECKS.each_key do |key|
49
+ table, = key.split(".")
50
+ next unless table_exists?(table)
51
+
52
+ remove_check_constraint table, name: self.class.constraint_name(key), if_exists: true
53
+ end
54
+ end
55
+
56
+ private
57
+
58
+ def set_lock_timeout
59
+ return unless postgres?
60
+
61
+ execute "SET LOCAL lock_timeout = '#{LOCK_TIMEOUT}'"
62
+ end
63
+
64
+ def list(values) = values.map { |value| connection.quote(value) }.join(", ")
65
+
66
+ # On Postgres, the spelling Postgres itself settles on once a schema.rb is
67
+ # loaded (`'x'::character varying::text`), so a host's schema dump after this
68
+ # migrate equals the dump after a load, byte for byte. An `IN (...)` list
69
+ # dumps as `ARRAY[...]::text[]` first and changes on the next load. Anywhere
70
+ # else (the engine's SQLite test host), the plain IN list.
71
+ def expression(column, values)
72
+ col = connection.quote_column_name(column)
73
+ return "#{col} IN (#{list(values)})" unless postgres?
74
+
75
+ array = values.map { |value| "#{connection.quote(value)}::character varying::text" }.join(", ")
76
+ "(#{col})::text = ANY (ARRAY[#{array}])"
77
+ end
78
+
79
+ def postgres? = connection.adapter_name.downcase.include?("postgres")
80
+
81
+ def refuse_strays!(table, column, values)
82
+ col = connection.quote_column_name(column)
83
+ strays = connection.select_rows(<<~SQL.squish)
84
+ SELECT #{col}, COUNT(*) FROM #{connection.quote_table_name(table)}
85
+ WHERE #{col} IS NOT NULL AND #{col} NOT IN (#{list(values)}) GROUP BY #{col} ORDER BY #{col}
86
+ SQL
87
+ return if strays.empty?
88
+
89
+ found = strays.map { |value, count| "#{value.inspect} (#{count})" }.join(", ")
90
+ raise ActiveRecord::MigrationError,
91
+ "#{table}.#{column} holds values outside #{values.inspect}: #{found}. " \
92
+ "Resolve those rows, then migrate again."
93
+ end
94
+ end
@@ -0,0 +1,69 @@
1
+ # CHECK users_role_known on the host's `users.role` (database audit 2026-11-07,
2
+ # section 3): the database half of Studio::Account's role validation, so a
3
+ # mistyped role is refused rather than saved as a quiet non-admin.
4
+ #
5
+ # THIS IS A MIGRATION AGAINST A HOST TABLE, shipped like the standard profile
6
+ # columns (20260813220000): install-copied with
7
+ # `bin/rails studio_engine:install:migrations`, never auto-run, and safe on an
8
+ # app that already disagrees.
9
+ #
10
+ # * No `users` table, no `role` column, or a role that is not a string (an
11
+ # integer enum): skipped.
12
+ # * A CHECK named users_role_known already there: skipped. The hub and Turf
13
+ # installed their own on 2026-11-08, narrowed to viewer + admin, and a host's
14
+ # narrower CHECK is the stronger guard; this one is the ceiling.
15
+ # * A row holding a role outside the list: REFUSED, naming the values, with
16
+ # nothing written. A stray role is a product call (Turf's "user" meant
17
+ # viewer); this migration does not guess it.
18
+ #
19
+ # Then it fills a NULL role with "viewer", sets NOT NULL, and adds the CHECK.
20
+ #
21
+ # The list is SPELLED OUT, not read from Studio::Roles: a migration is a record
22
+ # that must still run years from now, and a live constant may move. Widening the
23
+ # engine's list is a new migration that replaces this CHECK.
24
+ class AddUsersRoleKnownCheck < ActiveRecord::Migration[7.2]
25
+ ROLES = %w[viewer member admin].freeze
26
+ NAME = "users_role_known"
27
+
28
+ def up
29
+ return unless string_role?
30
+ return if check_constraint_exists?(:users, name: NAME)
31
+
32
+ allowed = ROLES.map { |role| connection.quote(role) }.join(", ")
33
+ unknown = select_values("SELECT DISTINCT role FROM users WHERE role IS NOT NULL AND role NOT IN (#{allowed})")
34
+ if unknown.any?
35
+ raise ActiveRecord::MigrationError, <<~MSG
36
+ AddUsersRoleKnownCheck refused: users.role holds #{unknown.sort.map(&:inspect).join(', ')},
37
+ outside Studio::Roles (#{ROLES.join(', ')}). Move those rows to a known role in a
38
+ migration of this app's own (Turf moved "user" to "viewer"), then run this again.
39
+ MSG
40
+ end
41
+
42
+ execute "UPDATE users SET role = 'viewer' WHERE role IS NULL"
43
+ change_column_null :users, :role, false
44
+ add_check_constraint :users, "role IN (#{allowed})", name: NAME
45
+ end
46
+
47
+ # Removes the CHECK only when it is this migration's: one that names every
48
+ # engine role. A host's own users_role_known, which `up` left in place, is
49
+ # narrower (the hub's and Turf's name viewer and admin only) and stays. NOT
50
+ # NULL stays too: `up` cannot record whether the host had it already, and a
51
+ # NULL role is the one value no host wants back.
52
+ def down
53
+ return unless string_role?
54
+
55
+ ours = check_constraints(:users).find { |check| check.name == NAME }
56
+ return unless ours && ROLES.all? { |role| ours.expression.include?("'#{role}'") }
57
+
58
+ remove_check_constraint :users, name: NAME
59
+ end
60
+
61
+ private
62
+
63
+ def string_role?
64
+ return false unless table_exists?(:users)
65
+
66
+ column = columns(:users).find { |c| c.name == "role" }
67
+ column && %i[string text].include?(column.type)
68
+ end
69
+ end
@@ -0,0 +1,103 @@
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
+ 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)
59
+ Set the provider's client id and secret, and the app's Active Record encryption keys.
60
+ TEXT
61
+ end
62
+
63
+ def self.engine_migration
64
+ File.expand_path("../../../../db/migrate/20261108130000_#{MIGRATION_NAME}.rb", __dir__)
65
+ end
66
+
67
+ def self.next_version
68
+ Time.now.utc.strftime("%Y%m%d%H%M%S")
69
+ end
70
+
71
+ INITIALIZER_BODY = <<~RUBY
72
+ # frozen_string_literal: true
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
+ #
81
+ # Connections (studio-engine docs/CONNECTIONS.md). One Studio.define_connection
82
+ # per provider this app connects; each stays off until its client id and
83
+ # secret are set. Draw its routes in config/routes.rb with
84
+ # Studio.draw_connection_routes. The example below is a placeholder: no
85
+ # such provider exists.
86
+ #
87
+ # Studio.define_connection :files,
88
+ # label: "Example Files",
89
+ # env: { client_id: "EXAMPLE_FILES_CLIENT_ID", client_secret: "EXAMPLE_FILES_CLIENT_SECRET" },
90
+ # authorize_url: "https://files.example/oauth/authorize",
91
+ # token_url: "https://files.example/oauth/token",
92
+ # revoke_url: "https://files.example/oauth/revoke",
93
+ # scopes: %w[files.read],
94
+ # refresh: :rotating,
95
+ # account: :callback, account_param: "account_id", account_format: /\\A\\d{1,20}\\z/,
96
+ # filter_keys: %w[account_id]
97
+ #
98
+ # Who may connect (default: :require_admin from Studio::ErrorHandling):
99
+ # Studio.connection_admin_guard = :require_admin
100
+ RUBY
101
+ end
102
+ end
103
+ 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