maquina-generators 0.9.0 → 0.11.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 (169) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +201 -12
  3. data/lib/generators/maquina/app/USAGE +4 -0
  4. data/lib/generators/maquina/app/app_generator.rb +38 -7
  5. data/lib/generators/maquina/app/templates/README.md.erb +21 -0
  6. data/lib/generators/maquina/app/templates/app/views/home/index.html.erb +1 -1
  7. data/lib/generators/maquina/auth_flavor.rb +59 -0
  8. data/lib/generators/maquina/backstage_signin/backstage_signin.rb +320 -0
  9. data/lib/generators/maquina/backstage_signin/templates/test/integration/backstage_access_test.rb.tt +104 -0
  10. data/lib/generators/maquina/csp_reports/csp_reports_generator.rb +13 -1
  11. data/lib/generators/maquina/csp_reports/templates/app/models/mcp/tools/csp_reports.rb +71 -0
  12. data/lib/generators/maquina/csp_reports/templates/test/models/mcp/tools/csp_reports_test.rb +35 -0
  13. data/lib/generators/maquina/error_context/USAGE +22 -0
  14. data/lib/generators/maquina/error_context/error_context_generator.rb +51 -0
  15. data/lib/generators/maquina/mcp/USAGE +38 -0
  16. data/lib/generators/maquina/mcp/mcp_generator.rb +194 -0
  17. data/lib/generators/maquina/mcp/mcp_sibling_tools.rb +122 -0
  18. data/lib/generators/maquina/mcp/templates/app/controllers/concerns/mcp_authenticatable.rb +63 -0
  19. data/lib/generators/maquina/mcp/templates/app/controllers/mcp_controller.rb +205 -0
  20. data/lib/generators/maquina/mcp/templates/app/models/mcp/tool_definitions.rb +38 -0
  21. data/lib/generators/maquina/mcp/templates/app/models/mcp/tool_error.rb +17 -0
  22. data/lib/generators/maquina/mcp/templates/app/models/mcp/tools/app.rb +51 -0
  23. data/lib/generators/maquina/mcp/templates/app/models/mcp/tools.rb +83 -0
  24. data/lib/generators/maquina/mcp/templates/app/models/mcp/user_scope.rb +50 -0
  25. data/lib/generators/maquina/mcp/templates/config/initializers/mcp_cors.rb +38 -0
  26. data/lib/generators/maquina/mcp/templates/test/integration/mcp_conformance_test.rb +223 -0
  27. data/lib/generators/maquina/mcp/templates/test/integration/mcp_flow_test.rb.tt +65 -0
  28. data/lib/generators/maquina/mcp/templates/test/models/mcp/tools_test.rb.tt +145 -0
  29. data/lib/generators/maquina/mcp/templates/test/test_helpers/mcp_test_helper.rb.tt +103 -0
  30. data/lib/generators/maquina/mcp_tool/USAGE +26 -0
  31. data/lib/generators/maquina/mcp_tool/mcp_tool_generator.rb +239 -0
  32. data/lib/generators/maquina/mcp_tool/templates/test/models/mcp/tools/tool_test.rb.tt +49 -0
  33. data/lib/generators/maquina/mission_control_jobs/USAGE +5 -0
  34. data/lib/generators/maquina/mission_control_jobs/mission_control_jobs_generator.rb +21 -5
  35. data/lib/generators/maquina/mission_control_jobs/templates/app/views/backstage_dashboard/index.html.erb.tt +1 -1
  36. data/lib/generators/maquina/mission_control_jobs/templates/app/views/layouts/_admin_navigation.html.erb.tt +12 -11
  37. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/_filters.html.erb +1 -1
  38. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/_general_information.html.erb +1 -1
  39. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/_job.html.erb +1 -1
  40. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/jobs/failed/_job.html.erb +1 -1
  41. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/queues/_job.html.erb +1 -1
  42. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/shared/_job.html.erb +1 -1
  43. data/lib/generators/maquina/mission_control_jobs/templates/app/views/mission_control/jobs/workers/_worker.html.erb +1 -1
  44. data/lib/generators/maquina/oauth/USAGE +35 -0
  45. data/lib/generators/maquina/oauth/oauth_generator.rb +359 -0
  46. data/lib/generators/maquina/oauth/templates/app/controllers/connected_applications_controller.rb +26 -0
  47. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/authorization_servers_controller.rb +24 -0
  48. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/authorizations_controller.rb +92 -0
  49. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/protected_resources_controller.rb +14 -0
  50. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/revocations_controller.rb +20 -0
  51. data/lib/generators/maquina/oauth/templates/app/controllers/oauth/tokens_controller.rb +67 -0
  52. data/lib/generators/maquina/oauth/templates/app/models/access_token.rb +83 -0
  53. data/lib/generators/maquina/oauth/templates/app/models/connected_application.rb +49 -0
  54. data/lib/generators/maquina/oauth/templates/app/models/mcp.rb.tt +33 -0
  55. data/lib/generators/maquina/oauth/templates/app/models/oauth_authorization_code.rb +52 -0
  56. data/lib/generators/maquina/oauth/templates/app/models/oauth_client/metadata_fetcher.rb +195 -0
  57. data/lib/generators/maquina/oauth/templates/app/models/oauth_client.rb +50 -0
  58. data/lib/generators/maquina/oauth/templates/app/views/connected_applications/index.html.erb +43 -0
  59. data/lib/generators/maquina/oauth/templates/app/views/oauth/authorizations/error.html.erb +8 -0
  60. data/lib/generators/maquina/oauth/templates/app/views/oauth/authorizations/new.html.erb +36 -0
  61. data/lib/generators/maquina/oauth/templates/config/locales/oauth.en.yml +34 -0
  62. data/lib/generators/maquina/oauth/templates/config/locales/oauth.es.yml +34 -0
  63. data/lib/generators/maquina/oauth/templates/migration_create_access_tokens.rb.tt +20 -0
  64. data/lib/generators/maquina/oauth/templates/migration_create_oauth_authorization_codes.rb.tt +19 -0
  65. data/lib/generators/maquina/oauth/templates/migration_create_oauth_clients.rb.tt +14 -0
  66. data/lib/generators/maquina/oauth/templates/test/fixtures/access_tokens.yml +48 -0
  67. data/lib/generators/maquina/oauth/templates/test/fixtures/oauth_authorization_codes.yml +11 -0
  68. data/lib/generators/maquina/oauth/templates/test/fixtures/oauth_clients.yml +7 -0
  69. data/lib/generators/maquina/oauth/templates/test/integration/connected_applications_test.rb.tt +70 -0
  70. data/lib/generators/maquina/oauth/templates/test/integration/oauth_authorization_test.rb.tt +150 -0
  71. data/lib/generators/maquina/oauth/templates/test/integration/oauth_discovery_test.rb +44 -0
  72. data/lib/generators/maquina/oauth/templates/test/integration/oauth_tokens_test.rb +147 -0
  73. data/lib/generators/maquina/oauth/templates/test/models/access_token_test.rb.tt +80 -0
  74. data/lib/generators/maquina/oauth/templates/test/models/connected_application_test.rb +41 -0
  75. data/lib/generators/maquina/oauth/templates/test/models/oauth_authorization_code_test.rb +58 -0
  76. data/lib/generators/maquina/oauth/templates/test/test_helpers/oauth_test_helper.rb.tt +82 -0
  77. data/lib/generators/maquina/passkeys/USAGE +4 -2
  78. data/lib/generators/maquina/passkeys/passkeys_generator.rb +16 -11
  79. data/lib/generators/maquina/passkeys/templates/app/controllers/session/{passkeys_controller.rb → passkeys_controller.rb.tt} +6 -2
  80. data/lib/generators/maquina/passkeys/templates/config/locales/{passkeys.en.yml → passkeys.en.yml.tt} +15 -0
  81. data/lib/generators/maquina/passkeys/templates/config/locales/{passkeys.es.yml → passkeys.es.yml.tt} +15 -0
  82. data/lib/generators/maquina/passkeys/templates/test/integration/{passkeys_test.rb → passkeys_test.rb.tt} +6 -0
  83. data/lib/generators/maquina/rack_attack/rack_attack_generator.rb +4 -1
  84. data/lib/generators/maquina/rack_attack/templates/config/initializers/rack_attack.rb.tt +317 -4
  85. data/lib/generators/maquina/registration/registration_generator.rb +32 -0
  86. data/lib/generators/maquina/registration/templates/app/views/registrations/new.html.erb.tt +4 -0
  87. data/lib/generators/maquina/registration/templates/app/views/sessions/new.html.erb.tt +5 -0
  88. data/lib/generators/maquina/security/USAGE +12 -0
  89. data/lib/generators/maquina/security/security_generator.rb +79 -7
  90. data/lib/generators/maquina/security/templates/app/models/mcp/tools/security.rb.tt +114 -0
  91. data/lib/generators/maquina/security/templates/app/views/backstage_dashboard/index.html.erb.tt +1 -1
  92. data/lib/generators/maquina/security/templates/app/views/layouts/_admin_navigation.html.erb.tt +12 -11
  93. data/lib/generators/maquina/security/templates/test/models/mcp/tools/security_test.rb +99 -0
  94. data/lib/generators/maquina/solid_errors/USAGE +21 -10
  95. data/lib/generators/maquina/solid_errors/error_context_files.rb +82 -0
  96. data/lib/generators/maquina/solid_errors/solid_errors_generator.rb +52 -31
  97. data/lib/generators/maquina/solid_errors/templates/app/agents/errors_query.rb +86 -29
  98. data/lib/generators/maquina/solid_errors/templates/app/agents/failure_triage.rb +4 -2
  99. data/lib/generators/maquina/solid_errors/templates/app/agents/list_failures_tool.rb +9 -4
  100. data/lib/generators/maquina/solid_errors/templates/app/models/mcp/tools/solid_errors.rb.tt +132 -0
  101. data/lib/generators/maquina/solid_errors/templates/app/views/backstage_dashboard/index.html.erb.tt +1 -1
  102. data/lib/generators/maquina/solid_errors/templates/app/views/layouts/_admin_navigation.html.erb.tt +12 -11
  103. data/lib/generators/maquina/solid_errors/templates/app/views/solid_errors/errors/show/_actions.html.erb +0 -15
  104. data/lib/generators/maquina/solid_errors/templates/app/views/solid_errors/errors/show/_error_details.html.erb +5 -5
  105. data/lib/generators/maquina/solid_errors/templates/app/views/solid_errors/occurrences/_collection.html.erb +1 -1
  106. data/lib/generators/maquina/solid_errors/templates/config/initializers/error_context.rb +33 -0
  107. data/lib/generators/maquina/solid_errors/templates/test/models/mcp/tools/solid_errors_filters_test.rb +68 -0
  108. data/lib/generators/maquina/solid_errors/templates/test/models/mcp/tools/solid_errors_test.rb +109 -0
  109. data/lib/generators/maquina/solid_queue/USAGE +11 -0
  110. data/lib/generators/maquina/solid_queue/solid_queue_generator.rb +25 -1
  111. data/lib/generators/maquina/solid_queue/templates/app/models/mcp/tools/solid_queue.rb.tt +163 -0
  112. data/lib/generators/maquina/solid_queue/templates/test/models/mcp/tools/solid_queue_test.rb +99 -0
  113. data/lib/maquina_generators/version.rb +1 -1
  114. data/test/fixtures/error_context/0.10.0/app/agents/errors_query.rb +105 -0
  115. data/test/fixtures/error_context/0.10.0/app/agents/failure_triage.rb +21 -0
  116. data/test/fixtures/error_context/0.10.0/app/agents/list_failures_tool.rb +20 -0
  117. data/test/fixtures/error_context/0.10.0/app/models/mcp/tools/solid_errors.rb +81 -0
  118. data/test/fixtures/error_context/0.10.0/app/models/mcp/tools/solid_errors_write.rb +101 -0
  119. data/test/generators/maquina/app_generator_test.rb +67 -5
  120. data/test/generators/maquina/backstage_signin_test.rb +296 -0
  121. data/test/generators/maquina/csp_reports_generator_test.rb +125 -6
  122. data/test/generators/maquina/error_context_generator_test.rb +188 -0
  123. data/test/generators/maquina/mcp_generator_test.rb +429 -0
  124. data/test/generators/maquina/mcp_tool_generator_test.rb +235 -0
  125. data/test/generators/maquina/mission_control_jobs_generator_test.rb +23 -0
  126. data/test/generators/maquina/oauth_client_metadata_fetcher_test.rb +290 -0
  127. data/test/generators/maquina/oauth_generator_test.rb +568 -0
  128. data/test/generators/maquina/passkeys_generator_test.rb +62 -2
  129. data/test/generators/maquina/rack_attack_generator_test.rb +71 -0
  130. data/test/generators/maquina/rack_attack_rules_test.rb +304 -0
  131. data/test/generators/maquina/registration_generator_test.rb +62 -0
  132. data/test/generators/maquina/security_generator_test.rb +188 -13
  133. data/test/generators/maquina/solid_errors_generator_test.rb +299 -33
  134. data/test/generators/maquina/solid_queue_generator_test.rb +175 -25
  135. data/test/support/rails_auth_app.rb +48 -0
  136. data/test/test_helper.rb +1 -0
  137. metadata +90 -41
  138. data/lib/generators/maquina/solid_errors/templates/app/controllers/failures_mcp_controller.rb.tt +0 -65
  139. data/test/tmp/Gemfile +0 -2
  140. data/test/tmp/app/controllers/application_controller.rb +0 -3
  141. data/test/tmp/app/controllers/concerns/authentication.rb +0 -63
  142. data/test/tmp/app/controllers/registration/verification_resends_controller.rb +0 -38
  143. data/test/tmp/app/controllers/registration/verifications_controller.rb +0 -64
  144. data/test/tmp/app/controllers/registrations_controller.rb +0 -63
  145. data/test/tmp/app/controllers/session/verification_resends_controller.rb +0 -44
  146. data/test/tmp/app/controllers/session/verifications_controller.rb +0 -64
  147. data/test/tmp/app/controllers/sessions_controller.rb +0 -56
  148. data/test/tmp/app/helpers/authentication_helper.rb +0 -20
  149. data/test/tmp/app/jobs/authentication_cleanup_job.rb +0 -13
  150. data/test/tmp/app/mailers/verification_mailer.rb +0 -15
  151. data/test/tmp/app/models/account.rb +0 -5
  152. data/test/tmp/app/models/current.rb +0 -5
  153. data/test/tmp/app/models/email_verification.rb +0 -58
  154. data/test/tmp/app/models/session.rb +0 -18
  155. data/test/tmp/app/models/user.rb +0 -37
  156. data/test/tmp/app/views/registration/verifications/new.html.erb +0 -43
  157. data/test/tmp/app/views/registrations/new.html.erb +0 -39
  158. data/test/tmp/app/views/session/verifications/new.html.erb +0 -43
  159. data/test/tmp/app/views/sessions/new.html.erb +0 -40
  160. data/test/tmp/app/views/verification_mailer/verification_code.html.erb +0 -37
  161. data/test/tmp/app/views/verification_mailer/verification_code.text.erb +0 -11
  162. data/test/tmp/config/locales/clave.en.yml +0 -102
  163. data/test/tmp/config/locales/clave.es.yml +0 -102
  164. data/test/tmp/config/routes.rb +0 -12
  165. data/test/tmp/db/migrate/20261019191386_create_accounts.rb +0 -9
  166. data/test/tmp/db/migrate/20261019191387_create_users.rb +0 -17
  167. data/test/tmp/db/migrate/20261019191388_create_sessions.rb +0 -12
  168. data/test/tmp/db/migrate/20261019191389_create_email_verifications.rb +0 -17
  169. data/test/tmp/test/test_helpers/session_test_helper.rb +0 -19
@@ -0,0 +1,83 @@
1
+ # An OAuth grant: a one-hour access token and the refresh token that renews
2
+ # it, on one row (generated by maquina:oauth). Only SHA-256 digests are
3
+ # stored; the raw values are returned once, in the response that issues them.
4
+ class AccessToken < ApplicationRecord
5
+ ACCESS_TTL = 1.hour
6
+ SCOPES = %w[read write].freeze
7
+
8
+ class InvalidGrant < StandardError; end
9
+
10
+ belongs_to :user
11
+ belongs_to :oauth_client
12
+
13
+ scope :unrevoked, -> { where(revoked_at: nil) }
14
+
15
+ validate :scope_is_known
16
+
17
+ def self.digest(raw)
18
+ Digest::SHA256.hexdigest(raw.to_s)
19
+ end
20
+
21
+ # A space-separated scope string in SCOPES order, or nil when it names a
22
+ # scope this server does not grant. A blank request means read.
23
+ def self.normalize_scope(requested)
24
+ scopes = requested.to_s.split
25
+ return "read" if scopes.empty?
26
+
27
+ scopes.uniq.sort_by { |scope| SCOPES.index(scope) || SCOPES.size }.join(" ") if (scopes - SCOPES).empty?
28
+ end
29
+
30
+ # [raw access token, raw refresh token], returned once.
31
+ def self.issue!(user:, client:, scope:, resource:)
32
+ access, refresh = SecureRandom.urlsafe_base64(32), SecureRandom.urlsafe_base64(32)
33
+ create!(user: user, oauth_client: client, scope: scope, resource: resource, expires_at: ACCESS_TTL.from_now,
34
+ token_digest: digest(access), refresh_token_digest: digest(refresh))
35
+ [access, refresh]
36
+ end
37
+
38
+ # The live token for a raw access token: not revoked, not expired, and its
39
+ # user still let through Mcp.enabled_for? (app/models/mcp.rb). nil otherwise.
40
+ def self.authenticate(raw)
41
+ return if raw.blank?
42
+
43
+ token = unrevoked.where("expires_at > ?", Time.current).find_by(token_digest: digest(raw))
44
+ token if token && Mcp.enabled_for?(token.user)
45
+ end
46
+
47
+ # The unrevoked row a raw refresh token belongs to, or nil.
48
+ def self.find_by_refresh_token(raw)
49
+ unrevoked.find_by(refresh_token_digest: digest(raw)) if raw.present?
50
+ end
51
+
52
+ # Spends this row's refresh token: revokes the row and returns a new
53
+ # [raw access, raw refresh] pair with the same scope. Refresh tokens never
54
+ # expire, but they are bound to the client they were issued to and work
55
+ # once; anything else raises InvalidGrant.
56
+ def rotate!(client:)
57
+ raise InvalidGrant unless oauth_client == client && Mcp.enabled_for?(user)
58
+
59
+ transaction do
60
+ raise InvalidGrant unless self.class.unrevoked.where(id: id).update_all(revoked_at: Time.current) == 1
61
+
62
+ self.class.issue!(user: user, client: client, scope: scope, resource: resource)
63
+ end
64
+ end
65
+
66
+ def revoke!
67
+ update!(revoked_at: Time.current) unless revoked?
68
+ end
69
+
70
+ def revoked?
71
+ revoked_at.present?
72
+ end
73
+
74
+ def scopes
75
+ scope.to_s.split
76
+ end
77
+
78
+ private
79
+
80
+ def scope_is_known
81
+ errors.add(:scope, :inclusion) unless scopes.any? && (scopes - SCOPES).empty?
82
+ end
83
+ end
@@ -0,0 +1,49 @@
1
+ # An app a person has let into their account, with every grant it holds
2
+ # (generated by maquina:oauth). Not a table: it groups the person's
3
+ # unrevoked tokens by client. A token whose hour is up still counts while its
4
+ # refresh token works, so "connected" is not the same as "active".
5
+ class ConnectedApplication
6
+ attr_reader :user, :client, :tokens
7
+
8
+ def self.for(user)
9
+ AccessToken.unrevoked.where(user: user).includes(:oauth_client).group_by(&:oauth_client)
10
+ .map { |client, tokens| new(user: user, client: client, tokens: tokens) }
11
+ .sort_by(&:connected_at)
12
+ end
13
+
14
+ # Only among the person's own connections: anyone else's client, or an
15
+ # unknown id, is the same RecordNotFound.
16
+ def self.find(user, client_id)
17
+ self.for(user).find { |application| application.client.id.to_s == client_id.to_s } ||
18
+ raise(ActiveRecord::RecordNotFound)
19
+ end
20
+
21
+ def initialize(user:, client:, tokens:)
22
+ @user, @client, @tokens = user, client, tokens
23
+ end
24
+
25
+ def to_param
26
+ client.to_param
27
+ end
28
+
29
+ def scopes
30
+ tokens.flat_map(&:scopes).uniq.sort_by { |scope| AccessToken::SCOPES.index(scope) || AccessToken::SCOPES.size }
31
+ end
32
+
33
+ def last_used_at
34
+ tokens.filter_map(&:last_used_at).max
35
+ end
36
+
37
+ def connected_at
38
+ tokens.map(&:created_at).min
39
+ end
40
+
41
+ # Every one of the person's tokens for this client stops working at once,
42
+ # and codes it has not exchanged yet are thrown away.
43
+ def revoke!
44
+ AccessToken.transaction do
45
+ AccessToken.unrevoked.where(user: user, oauth_client: client).update_all(revoked_at: Time.current)
46
+ OauthAuthorizationCode.unused.where(user: user, oauth_client: client).delete_all
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,33 @@
1
+ # The app's MCP server (generated by maquina:oauth): the protocol revision it
2
+ # speaks, its version, and the one gate every MCP check goes through.
3
+ module Mcp
4
+ PROTOCOL_VERSION = "2026-07-28"
5
+ SERVER_VERSION = "0.1.0"
6
+
7
+ # The feature flag that gates MCP, or nil for no gate.
8
+ FLAG = <%= flag_name ? ":#{flag_name}" : "nil" %>
9
+
10
+ # Every MCP gate calls this: the OAuth scope, the consent screen, the
11
+ # Connected apps page and the tools a token can see. The app owns this
12
+ # method; swap in Flipper, a column on users or an account plan as needed.
13
+ #
14
+ # With a FLAG, it reads credentials (features: { <flag>: true }) and then
15
+ # the upcased ENV variable.
16
+ <% if clave? -%>
17
+ #
18
+ # A blocked user is turned away everywhere, tokens and codes included.
19
+ def self.enabled_for?(user)
20
+ return false if user&.blocked?
21
+ return true if FLAG.nil?
22
+ <% else -%>
23
+ #
24
+ # Tokens and codes are checked here too, so a check that turns a person away
25
+ # (a deactivated user, a suspended account) goes first:
26
+ # return false unless user&.active?
27
+ def self.enabled_for?(user)
28
+ return true if FLAG.nil?
29
+ <% end -%>
30
+
31
+ ActiveModel::Type::Boolean.new.cast(Rails.application.credentials.dig(:features, FLAG) || ENV[FLAG.to_s.upcase]) == true
32
+ end
33
+ end
@@ -0,0 +1,52 @@
1
+ # A single-use authorization code (generated by maquina:oauth). Only the
2
+ # SHA-256 digest is stored; the raw code exists in the redirect that hands it
3
+ # to the client and nowhere else.
4
+ class OauthAuthorizationCode < ApplicationRecord
5
+ TTL = 10.minutes
6
+ # RFC 7636: 43-128 characters from the unreserved set.
7
+ VERIFIER = /\A[A-Za-z0-9\-._~]{43,128}\z/
8
+
9
+ # One error for every way a redemption fails, so a caller learns nothing
10
+ # about which check it missed.
11
+ class InvalidGrant < StandardError; end
12
+
13
+ belongs_to :user
14
+ belongs_to :oauth_client
15
+
16
+ scope :unused, -> { where(used_at: nil) }
17
+
18
+ # The raw code, returned once.
19
+ def self.issue!(user:, client:, redirect_uri:, code_challenge:, scope:, resource:)
20
+ raw = SecureRandom.urlsafe_base64(32)
21
+ create!(user: user, oauth_client: client, code_digest: AccessToken.digest(raw), code_challenge: code_challenge,
22
+ redirect_uri: redirect_uri, scope: scope, resource: resource, expires_at: TTL.from_now)
23
+ raw
24
+ end
25
+
26
+ # The code, now spent. Raises InvalidGrant unless it is known, unexpired,
27
+ # unused, issued to this client for this exact redirect_uri, and the
28
+ # verifier hashes to its PKCE challenge.
29
+ def self.redeem!(raw, client:, redirect_uri:, verifier:)
30
+ code = find_by(code_digest: AccessToken.digest(raw))
31
+ raise InvalidGrant unless code&.redeemable?(client: client, redirect_uri: redirect_uri, verifier: verifier)
32
+ # Claimed in one statement, so two requests racing with the same code get
33
+ # one success between them.
34
+ raise InvalidGrant unless unused.where(id: code.id).update_all(used_at: Time.current) == 1
35
+
36
+ code
37
+ end
38
+
39
+ def redeemable?(client:, redirect_uri:, verifier:)
40
+ used_at.nil? && expires_at.future? && oauth_client == client && Mcp.enabled_for?(user) &&
41
+ redirect_uri.to_s == self.redirect_uri && verifier_matches?(verifier)
42
+ end
43
+
44
+ private
45
+
46
+ def verifier_matches?(verifier)
47
+ return false unless verifier.to_s.match?(VERIFIER)
48
+
49
+ challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)
50
+ ActiveSupport::SecurityUtils.secure_compare(challenge, code_challenge)
51
+ end
52
+ end
@@ -0,0 +1,195 @@
1
+ require "ipaddr"
2
+ require "json"
3
+ require "net/http"
4
+ require "openssl"
5
+ require "resolv"
6
+ require "timeout"
7
+
8
+ # Fetches a Client ID Metadata Document (generated by maquina:oauth).
9
+ #
10
+ # An MCP client's client_id is an https URL that serves its own metadata, so
11
+ # signing in means fetching a URL a stranger chose. Everything that could turn
12
+ # that fetch into a probe of the server's own network is refused before a byte
13
+ # is sent, and everything that could make it slow or large is cut short:
14
+ #
15
+ # - a URL that is not https, has no path, or names its host as an IP
16
+ # - a host that resolves to a loopback, private, link-local, unspecified or
17
+ # carrier-grade NAT address (BLOCKED_RANGES)
18
+ # - any redirect, which is never followed
19
+ # - a body over MAX_BYTES, or an exchange that takes longer than TIMEOUT
20
+ # - a body that is not a JSON object, or whose client_id is not the URL it
21
+ # was fetched from, or that lacks client_name or redirect_uris
22
+ #
23
+ # Accepted gap (DNS rebinding): the host is resolved here and again by
24
+ # Net::HTTP when it connects, so a name with a very short TTL could answer a
25
+ # public address to the check and a private one to the connection.
26
+ #
27
+ # Plain Ruby (Net::HTTP, Resolv, IPAddr) so it loads and is tested outside Rails.
28
+ class OauthClient
29
+ class MetadataFetcher
30
+ class Refused < StandardError; end
31
+
32
+ MAX_BYTES = 16_384
33
+ TIMEOUT = 3
34
+
35
+ BLOCKED_RANGES = %w[
36
+ 0.0.0.0/8 10.0.0.0/8 100.64.0.0/10 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12
37
+ 192.168.0.0/16 224.0.0.0/4 240.0.0.0/4
38
+ ::/128 ::1/128 fc00::/7 fe80::/10 ff00::/8
39
+ ].map { |range| IPAddr.new(range) }.freeze
40
+
41
+ # A host written as numbers ("2130706433", "0x7f.1") is an IP however it
42
+ # is spelled; no real top-level domain is numeric.
43
+ NUMERIC_HOST = /\A(0x\h+|\d+)(\.(0x\h+|\d+))*\.?\z/i
44
+
45
+ # redirect_uri schemes a browser would run or read locally instead of
46
+ # handing the code to a client.
47
+ UNSAFE_SCHEMES = %w[javascript data vbscript file].freeze
48
+
49
+ class << self
50
+ # Addresses let through despite BLOCKED_RANGES. Empty in an app: it exists
51
+ # only so the test suite can reach a TLS server on localhost, together with
52
+ # the ca_file: argument to fetch.
53
+ attr_writer :permitted_addresses
54
+
55
+ def permitted_addresses
56
+ @permitted_addresses ||= []
57
+ end
58
+
59
+ def fetch(client_id, ca_file: nil)
60
+ new(client_id, ca_file: ca_file).fetch
61
+ end
62
+
63
+ def blocked_address?(address)
64
+ ip = IPAddr.new(address.to_s)
65
+ ip = ip.native if ip.ipv4_mapped?
66
+ return false if permitted_addresses.any? { |permitted| IPAddr.new(permitted.to_s) == ip }
67
+
68
+ BLOCKED_RANGES.any? { |range| range.family == ip.family && range.include?(ip) }
69
+ rescue IPAddr::InvalidAddressError
70
+ true
71
+ end
72
+ end
73
+
74
+ def initialize(client_id, ca_file: nil)
75
+ @client_id = client_id.to_s
76
+ @ca_file = ca_file
77
+ end
78
+
79
+ # The metadata document as a Hash, or Refused with the reason.
80
+ def fetch
81
+ uri = parse_client_id
82
+ check_host(uri.hostname)
83
+ validate(parse_document(download(uri)))
84
+ end
85
+
86
+ private
87
+
88
+ def parse_client_id
89
+ uri = URI.parse(@client_id)
90
+ refuse "client_id must be an https URL" unless uri.is_a?(URI::HTTPS) && uri.hostname.to_s != ""
91
+ refuse "client_id must have a path" if uri.path.to_s == "" || uri.path == "/"
92
+ refuse "client_id must not carry credentials or a fragment" if uri.userinfo || uri.fragment
93
+ uri
94
+ rescue URI::InvalidURIError
95
+ refuse "client_id is not a URL"
96
+ end
97
+
98
+ def check_host(host)
99
+ refuse "client_id must name a host, not an IP address" if ip_literal?(host)
100
+
101
+ addresses = resolver.getaddresses(host)
102
+ refuse "client_id host does not resolve" if addresses.empty?
103
+ refuse "client_id host resolves to a private address" if addresses.any? { |address| self.class.blocked_address?(address) }
104
+ end
105
+
106
+ def ip_literal?(host)
107
+ IPAddr.new(host)
108
+ true
109
+ rescue IPAddr::InvalidAddressError
110
+ host.match?(NUMERIC_HOST)
111
+ end
112
+
113
+ def resolver
114
+ dns = Resolv::DNS.new
115
+ dns.timeouts = TIMEOUT
116
+ Resolv.new([Resolv::Hosts.new, dns])
117
+ end
118
+
119
+ # The per-read timeouts alone would let a server trickle its status line
120
+ # and headers a byte at a time and hold the request open indefinitely, so
121
+ # the whole exchange also runs under one TIMEOUT budget.
122
+ def download(uri)
123
+ body = +""
124
+
125
+ Timeout.timeout(TIMEOUT) do
126
+ Net::HTTP.start(uri.hostname, uri.port, **connection_options) do |http|
127
+ request = Net::HTTP::Get.new(uri, "Accept" => "application/json")
128
+ http.request(request) do |response|
129
+ refuse "client_id redirects; redirects are not followed" if response.is_a?(Net::HTTPRedirection)
130
+ refuse "client_id answered #{response.code}" unless response.is_a?(Net::HTTPSuccess)
131
+ refuse "client metadata is too large" if response.content_length.to_i > MAX_BYTES
132
+
133
+ response.read_body do |chunk|
134
+ body << chunk
135
+ refuse "client metadata is too large" if body.bytesize > MAX_BYTES
136
+ end
137
+ end
138
+ end
139
+ end
140
+
141
+ body
142
+ rescue Timeout::Error # Net::OpenTimeout, ReadTimeout and WriteTimeout too
143
+ refuse "client_id took too long to answer"
144
+ rescue SocketError, SystemCallError, IOError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse
145
+ refuse "client_id could not be reached over TLS"
146
+ end
147
+
148
+ # max_retries: 0, or Net::HTTP retries a timed-out GET and doubles the wait.
149
+ def connection_options
150
+ options = {use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_PEER, max_retries: 0,
151
+ open_timeout: TIMEOUT, read_timeout: TIMEOUT, write_timeout: TIMEOUT, ssl_timeout: TIMEOUT}
152
+ options[:ca_file] = @ca_file if @ca_file
153
+ options
154
+ end
155
+
156
+ def parse_document(body)
157
+ document = JSON.parse(body)
158
+ refuse "client metadata is not a JSON object" unless document.is_a?(Hash)
159
+ document
160
+ rescue JSON::ParserError
161
+ refuse "client metadata is not JSON"
162
+ end
163
+
164
+ def validate(document)
165
+ refuse "client metadata client_id does not match its URL" unless document["client_id"] == @client_id
166
+ refuse "client metadata has no client_name" unless present_string?(document["client_name"])
167
+
168
+ redirect_uris = document["redirect_uris"]
169
+ unless redirect_uris.is_a?(Array) && redirect_uris.any? && redirect_uris.all? { |uri| redirect_uri?(uri) }
170
+ refuse "client metadata has no valid redirect_uris"
171
+ end
172
+
173
+ document
174
+ end
175
+
176
+ def redirect_uri?(value)
177
+ return false unless present_string?(value)
178
+
179
+ # A redirect target the authorize endpoint can append a query to: no
180
+ # opaque URI (javascript:alert(1), mailto:x) and no fragment.
181
+ uri = URI.parse(value)
182
+ uri.absolute? && uri.opaque.nil? && uri.fragment.nil? && !UNSAFE_SCHEMES.include?(uri.scheme.downcase)
183
+ rescue URI::InvalidURIError
184
+ false
185
+ end
186
+
187
+ def present_string?(value)
188
+ value.is_a?(String) && !value.strip.empty?
189
+ end
190
+
191
+ def refuse(reason)
192
+ raise Refused, reason
193
+ end
194
+ end
195
+ end
@@ -0,0 +1,50 @@
1
+ # An MCP client, known by its Client ID Metadata Document (generated by
2
+ # maquina:oauth). The client_id is the https URL of that document; there is
3
+ # no registration endpoint and no client secret.
4
+ class OauthClient < ApplicationRecord
5
+ METADATA_TTL = 24.hours
6
+
7
+ has_many :oauth_authorization_codes, dependent: :destroy
8
+ has_many :access_tokens, dependent: :destroy
9
+
10
+ serialize :redirect_uris, coder: JSON
11
+
12
+ validates :client_id, presence: true, uniqueness: true
13
+ validates :client_name, :metadata_fetched_at, presence: true
14
+
15
+ # The client for a client_id, fetched (MetadataFetcher) when it is new or
16
+ # its stored copy is older than METADATA_TTL. Raises
17
+ # MetadataFetcher::Refused when the document cannot be trusted.
18
+ def self.from_metadata!(client_id)
19
+ client = find_or_initialize_by(client_id: client_id)
20
+ return client if client.persisted? && client.metadata_fresh?
21
+
22
+ metadata = MetadataFetcher.fetch(client_id)
23
+ client.update!(client_name: metadata["client_name"].strip.truncate(100),
24
+ redirect_uris: metadata["redirect_uris"], metadata_fetched_at: Time.current)
25
+ client
26
+ rescue ActiveRecord::RecordNotUnique
27
+ # Two first fetches of the same document raced and the other one stored
28
+ # it first (caught by the unique index here, by the uniqueness check
29
+ # below): its copy is just as fresh.
30
+ find_by!(client_id: client_id)
31
+ rescue ActiveRecord::RecordInvalid => error
32
+ raise unless error.record.errors.of_kind?(:client_id, :taken)
33
+
34
+ find_by!(client_id: client_id)
35
+ end
36
+
37
+ def metadata_fresh?
38
+ metadata_fetched_at.present? && metadata_fetched_at > METADATA_TTL.ago
39
+ end
40
+
41
+ # Exact match only: no prefix, no port or path leniency.
42
+ def redirect_uri?(uri)
43
+ Array(redirect_uris).include?(uri)
44
+ end
45
+
46
+ # The domain shown on the consent screen, so people see who is really asking.
47
+ def host
48
+ URI(client_id).host
49
+ end
50
+ end
@@ -0,0 +1,43 @@
1
+ <div class="flex flex-1 justify-center px-4 py-8">
2
+ <div class="w-full max-w-2xl space-y-6">
3
+ <div>
4
+ <h1 class="text-2xl font-bold text-foreground"><%= t(".title") %></h1>
5
+ <p class="mt-1 text-sm text-muted-foreground"><%= t(".description") %></p>
6
+ </div>
7
+
8
+ <% if @connected_applications.empty? %>
9
+ <div class="bg-card rounded-xl border border-border p-8 text-center">
10
+ <p class="text-sm text-muted-foreground"><%= t(".empty") %></p>
11
+ </div>
12
+ <% else %>
13
+ <ul class="bg-card rounded-xl border border-border divide-y divide-border">
14
+ <% @connected_applications.each do |connected_application| %>
15
+ <% client = connected_application.client %>
16
+ <li id="<%= dom_id(client, :connected) %>" class="flex flex-wrap items-center gap-4 p-4">
17
+ <div class="flex-1 min-w-0 space-y-1">
18
+ <p class="text-sm font-medium text-foreground"><%= client.client_name %></p>
19
+ <p class="text-xs text-muted-foreground"><%= client.host %></p>
20
+ <p class="flex flex-wrap gap-1">
21
+ <% connected_application.scopes.each do |scope| %>
22
+ <span data-component="badge" data-variant="secondary" class="text-xs font-medium"><%= t(".scopes.#{scope}") %></span>
23
+ <% end %>
24
+ </p>
25
+ </div>
26
+
27
+ <div class="text-xs text-muted-foreground space-y-1">
28
+ <p><%= t(".connected", date: l(connected_application.connected_at.to_date, format: :long)) %></p>
29
+ <p>
30
+ <%= connected_application.last_used_at ? t(".last_used", time: time_ago_in_words(connected_application.last_used_at)) : t(".never_used") %>
31
+ </p>
32
+ </div>
33
+
34
+ <%= button_to t(".revoke"), connected_app_path(client), method: :delete,
35
+ form: { data: { turbo_confirm: t(".revoke_confirm", name: client.client_name) } },
36
+ data: { component: "button", variant: "ghost" },
37
+ class: "px-3 py-2 text-sm font-medium text-destructive hover:bg-destructive/10 rounded-lg cursor-pointer" %>
38
+ </li>
39
+ <% end %>
40
+ </ul>
41
+ <% end %>
42
+ </div>
43
+ </div>
@@ -0,0 +1,8 @@
1
+ <div class="flex flex-1 items-center justify-center px-4 py-8">
2
+ <div class="w-full max-w-md">
3
+ <div class="bg-card rounded-xl shadow-sm border border-border p-8 space-y-4 text-center">
4
+ <h1 class="text-2xl font-bold text-foreground"><%= t(".title") %></h1>
5
+ <p class="text-sm text-muted-foreground"><%= t(".#{@reason}") %></p>
6
+ </div>
7
+ </div>
8
+ </div>
@@ -0,0 +1,36 @@
1
+ <div class="flex flex-1 items-center justify-center px-4 py-8">
2
+ <div class="w-full max-w-md">
3
+ <div class="bg-card rounded-xl shadow-sm border border-border p-8 space-y-6">
4
+ <div class="space-y-2 text-center">
5
+ <h1 class="text-2xl font-bold text-foreground"><%= t(".title", client_name: @client.client_name) %></h1>
6
+ <p class="text-sm text-muted-foreground"><%= @client.host %></p>
7
+ </div>
8
+
9
+ <p class="text-sm text-foreground"><%= t(".signed_in_as", email: Current.user.email_address) %></p>
10
+
11
+ <div class="space-y-2">
12
+ <p class="text-sm font-medium text-foreground"><%= t(".requested") %></p>
13
+ <ul class="space-y-1 text-sm text-muted-foreground">
14
+ <% @oauth_params[:scope].split.each do |scope| %>
15
+ <li><%= t(".scopes.#{scope}") %></li>
16
+ <% end %>
17
+ </ul>
18
+ </div>
19
+
20
+ <%# A plain form post, not Turbo: the answer is a redirect to the app's own
21
+ address, which a fetch would refuse to follow across origins. %>
22
+ <%= form_with url: oauth_authorization_path, method: :post, data: { turbo: false }, class: "flex gap-3" do |form| %>
23
+ <% @oauth_params.each do |name, value| %>
24
+ <%= hidden_field_tag name, value, id: nil %>
25
+ <% end %>
26
+
27
+ <%= form.button t(".allow"), name: "decision", value: "allow",
28
+ data: { component: "button", variant: "primary" },
29
+ class: "flex-1 px-4 py-3 text-base font-medium text-primary-foreground bg-primary hover:bg-primary/90 rounded-lg transition-colors cursor-pointer" %>
30
+ <%= form.button t(".cancel"), name: "decision", value: "deny",
31
+ data: { component: "button", variant: "ghost" },
32
+ class: "flex-1 px-4 py-3 text-base font-medium text-foreground hover:bg-accent rounded-lg transition-colors cursor-pointer" %>
33
+ <% end %>
34
+ </div>
35
+ </div>
36
+ </div>
@@ -0,0 +1,34 @@
1
+ en:
2
+ flash:
3
+ connected_applications:
4
+ destroyed: "%{name} can no longer use your account."
5
+
6
+ oauth:
7
+ authorizations:
8
+ new:
9
+ title: "Allow %{client_name} to use your account?"
10
+ signed_in_as: "Signed in as %{email}"
11
+ requested: "It's asking to:"
12
+ scopes:
13
+ read: "read: see your data"
14
+ write: "write: make changes for you"
15
+ allow: "Allow"
16
+ cancel: "Cancel"
17
+ error:
18
+ title: "This app can't connect"
19
+ unknown_client: "We couldn't verify this app. Its address doesn't point to a valid app description."
20
+ redirect_mismatch: "This app asked to send you back to an address it hasn't registered."
21
+
22
+ connected_applications:
23
+ index:
24
+ title: "Connected apps"
25
+ description: "Apps you've allowed to use your account, such as AI assistants. Revoke one and it loses access right away."
26
+ empty: "No apps are connected to your account."
27
+ scopes:
28
+ read: "Read"
29
+ write: "Write"
30
+ connected: "Connected %{date}"
31
+ last_used: "Last used %{time} ago"
32
+ never_used: "Not used yet"
33
+ revoke: "Revoke"
34
+ revoke_confirm: "Revoke %{name}? It will lose access to your account right away."
@@ -0,0 +1,34 @@
1
+ es:
2
+ flash:
3
+ connected_applications:
4
+ destroyed: "%{name} ya no puede usar tu cuenta."
5
+
6
+ oauth:
7
+ authorizations:
8
+ new:
9
+ title: "¿Permitir que %{client_name} use tu cuenta?"
10
+ signed_in_as: "Sesión iniciada como %{email}"
11
+ requested: "Solicita:"
12
+ scopes:
13
+ read: "lectura: ver tus datos"
14
+ write: "escritura: hacer cambios por ti"
15
+ allow: "Permitir"
16
+ cancel: "Cancelar"
17
+ error:
18
+ title: "Esta app no se puede conectar"
19
+ unknown_client: "No pudimos verificar esta app. Su dirección no apunta a una descripción de app válida."
20
+ redirect_mismatch: "Esta app pidió enviarte de vuelta a una dirección que no tiene registrada."
21
+
22
+ connected_applications:
23
+ index:
24
+ title: "Apps conectadas"
25
+ description: "Apps a las que permitiste usar tu cuenta, como asistentes de IA. Si revocas una, pierde el acceso de inmediato."
26
+ empty: "No hay apps conectadas a tu cuenta."
27
+ scopes:
28
+ read: "Lectura"
29
+ write: "Escritura"
30
+ connected: "Conectada el %{date}"
31
+ last_used: "Usada por última vez hace %{time}"
32
+ never_used: "Aún no se ha usado"
33
+ revoke: "Revocar"
34
+ revoke_confirm: "¿Revocar %{name}? Perderá el acceso a tu cuenta de inmediato."
@@ -0,0 +1,20 @@
1
+ class CreateAccessTokens < ActiveRecord::Migration<%= migration_version %>
2
+ def change
3
+ create_table :access_tokens do |t|
4
+ t.references :user, null: false, foreign_key: true
5
+ t.references :oauth_client, null: false, foreign_key: true
6
+ t.string :token_digest, null: false
7
+ t.string :refresh_token_digest, null: false
8
+ t.string :scope, null: false
9
+ t.string :resource, null: false
10
+ t.datetime :expires_at, null: false
11
+ t.datetime :last_used_at
12
+ t.datetime :revoked_at
13
+
14
+ t.timestamps
15
+ end
16
+
17
+ add_index :access_tokens, :token_digest, unique: true
18
+ add_index :access_tokens, :refresh_token_digest, unique: true
19
+ end
20
+ end
@@ -0,0 +1,19 @@
1
+ class CreateOauthAuthorizationCodes < ActiveRecord::Migration<%= migration_version %>
2
+ def change
3
+ create_table :oauth_authorization_codes do |t|
4
+ t.references :user, null: false, foreign_key: true
5
+ t.references :oauth_client, null: false, foreign_key: true
6
+ t.string :code_digest, null: false
7
+ t.string :code_challenge, null: false
8
+ t.string :redirect_uri, null: false
9
+ t.string :scope, null: false
10
+ t.string :resource, null: false
11
+ t.datetime :expires_at, null: false
12
+ t.datetime :used_at
13
+
14
+ t.timestamps
15
+ end
16
+
17
+ add_index :oauth_authorization_codes, :code_digest, unique: true
18
+ end
19
+ end