samagotchi 0.182.0 → 0.183.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 (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -1
@@ -0,0 +1,814 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's OAuth part (manifest.yml plugin: parts:, loaded after
4
+ # http_client.rb, whose Refused NeedsSignIn subclasses, and before plugin.rb):
5
+ # signing in to a remote MCP server that answers 401 (the MCP spec's
6
+ # authorization, revision 2026-07-28). Discovery (the server's protected
7
+ # resource metadata, then its provider's metadata), the client chi signs in
8
+ # as (one configured by hand, else a registration of its own), PKCE, the
9
+ # code's exchange, and the token object HttpClient sends (OAuth::Token).
10
+ # plugin.rb keeps the wiring: /mcp login|logout, the server's state, the
11
+ # cards. What it shows or logs never holds a token, a code, a verifier, a
12
+ # client secret or a whole authorize address: an error here is one plain
13
+ # line (Refusal) naming at most an origin.
14
+ require "digest"
15
+ require "ipaddr"
16
+ require "json"
17
+ require "openssl"
18
+ require "securerandom"
19
+ require "socket"
20
+ require "strscan"
21
+ require "uri"
22
+ require "samagotchi/cancellation_controller"
23
+
24
+ class Plugin
25
+ module OAuth
26
+ # A sign-in step that can't go on, its message the card's line.
27
+ class Refusal < StandardError
28
+ # The flow's card to replace with it (nil before the flow started).
29
+ attr_accessor :card_id
30
+ end
31
+
32
+ # The provider doesn't know the client chi signed in as (invalid_client):
33
+ # one fresh registration, once.
34
+ class InvalidClient < Refusal; end
35
+
36
+ # The server's sign-in is gone (none kept, renewing refused): the user
37
+ # signs in again. A 401, as HttpClient's own.
38
+ class NeedsSignIn < HttpClient::Refused
39
+ def initialize(message = "needs sign-in (401)")
40
+ super(message, status: 401)
41
+ end
42
+ end
43
+
44
+ # Each fetch of sign-in data: its timeout and the most of a body read.
45
+ FETCH_TIMEOUT = 10
46
+ BODY_BYTES = 256 * 1024
47
+ # The token exchange and the revocation.
48
+ EXCHANGE_TIMEOUT = 15
49
+ REVOKE_TIMEOUT = 5
50
+ # How long a sign-in waits for the browser (ctx.sign_in's default).
51
+ SIGN_IN_TIMEOUT = 300
52
+ # The redirect address a registration names besides the exact one.
53
+ LOOPBACK_REDIRECT = "http://127.0.0.1/callback"
54
+
55
+ # Where a sign-in's data may not come from unless the server itself is
56
+ # on a loopback host (RFC 9728 §7.7): loopback, private, link-local,
57
+ # shared (100.64/10, a tailnet's) and unique-local addresses.
58
+ INTERNAL = %w[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 192.168.0.0/16
59
+ ::/128 ::1/128 fc00::/7 fe80::/10].map { |range| IPAddr.new(range) }.freeze
60
+
61
+ # 16 hex of a SHA-256: a secret's name for an address.
62
+ def self.key(text) = Digest::SHA256.hexdigest(text.to_s)[0, 16]
63
+
64
+ # The secret holding the sign-in for +resource+ (a canonical url).
65
+ def self.token_name(resource) = "oauth-#{key(resource)}"
66
+
67
+ # The secret holding chi's registration with the provider +issuer+.
68
+ def self.client_name(issuer) = "client-#{key(issuer)}"
69
+
70
+ # The url as a resource indicator (RFC 8707, the MCP spec's canonical
71
+ # form): scheme and host lower-cased, no default port, no fragment, no
72
+ # trailing slash. Nil for an address that isn't one.
73
+ def self.canonical(url)
74
+ uri = URI.parse(url.to_s)
75
+ return nil unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
76
+
77
+ port = uri.port == uri.default_port ? "" : ":#{uri.port}"
78
+ query = uri.query ? "?#{uri.query}" : ""
79
+ "#{uri.scheme.downcase}://#{uri.host.downcase}#{port}#{uri.path.to_s.sub(%r{/+\z}, "")}#{query}"
80
+ rescue URI::Error
81
+ nil
82
+ end
83
+
84
+ def self.origin(url) = HttpClient.origin(url)
85
+
86
+ def self.loopback_host?(host) = %w[127.0.0.1 ::1 [::1] localhost].include?(host.to_s.downcase)
87
+
88
+ # Printable ASCII only, at most +max+: a provider's error code or
89
+ # description on a card (never a control character).
90
+ def self.plain(text, max)
91
+ text.to_s.gsub(/[^\x20-\x7e]/, "")[0, max]
92
+ end
93
+
94
+ # A sign-out's best-effort revocation (RFC 7009) of the kept sign-in:
95
+ # its refresh token, else its access token, at the kept endpoint. A
96
+ # failure is only logged (its class).
97
+ def self.revoke(http, kept, log:)
98
+ endpoint = kept["revocation_endpoint"]
99
+ return unless endpoint.is_a?(String)
100
+
101
+ hint = kept["refresh_token"] ? "refresh_token" : "access_token"
102
+ form = { token: kept[hint], token_type_hint: hint, client_id: kept["client_id"],
103
+ client_secret: kept["client_secret"] }.compact
104
+ res = http.request("POST", endpoint, body: URI.encode_www_form(form), timeout: REVOKE_TIMEOUT,
105
+ headers: { "Content-Type" => "application/x-www-form-urlencoded" },
106
+ cancel: Samagotchi::CancellationController.new)
107
+ log.call("oauth_revoked", status: res.status)
108
+ rescue Samagotchi::Plugin::HttpError, ArgumentError => e
109
+ log.call("oauth_not_revoked", error: e.class.name)
110
+ end
111
+
112
+ # The Bearer challenge's parameters in a WWW-Authenticate value, which
113
+ # may hold several challenges (Net::HTTP joins repeated headers with
114
+ # ", "): {"resource_metadata" => …, "scope" => …}, {} without one.
115
+ def self.challenge(header)
116
+ challenges = []
117
+ scanner = StringScanner.new(header.to_s)
118
+ token = /[!#$%&'*+\-.^_`|~0-9A-Za-z]+/
119
+ until scanner.eos?
120
+ scanner.skip(/[\s,]+/)
121
+ break if scanner.eos?
122
+
123
+ if scanner.scan(/(#{token})\s*=\s*/o)
124
+ name = scanner[1].downcase
125
+ value = scanner.scan(/"((?:[^"\\]|\\.)*)"/) ? scanner[1].gsub(/\\(.)/, '\1') : scanner.scan(/[^\s,]*/)
126
+ challenges.last[1][name] ||= value if challenges.last
127
+ elsif scanner.scan(token)
128
+ challenges << [scanner.matched.downcase, {}]
129
+ scanner.skip(%r{[ \t]+[A-Za-z0-9\-._~+/]+=*(?=[ \t]*(?:,|\z))}) # a token68
130
+ else
131
+ scanner.getch
132
+ end
133
+ end
134
+ challenges.find { |scheme, _| scheme == "bearer" }&.last || {}
135
+ end
136
+
137
+ # A provider, as its metadata says (validated): +iss_required+ whether a
138
+ # callback must carry iss (authorization_response_iss_parameter_supported),
139
+ # +cimd+ whether it takes a client id metadata document, +scope+ the one
140
+ # to ask for (nil: none).
141
+ Provider = Data.define(:issuer, :authorization_endpoint, :token_endpoint, :registration_endpoint,
142
+ :revocation_endpoint, :iss_required, :cimd, :scope)
143
+
144
+ # The client chi signs in as: +kind+ :config, :cimd or :dcr; +port+ the
145
+ # redirect port it needs (nil: any); +fresh+ a registration made by this
146
+ # login (an invalid_client then isn't a stale one).
147
+ Registration = Data.define(:kind, :client_id, :client_secret, :port, :fresh) do
148
+ def inspect = "#<Registration #{kind} port=#{port.inspect}>"
149
+
150
+ alias_method :to_s, :inspect
151
+ end
152
+
153
+ # The sign-in data fetches: https only (http on a loopback host when the
154
+ # server's url is on one), never to an internal address (unless the
155
+ # server is on a loopback host), no redirect followed, a body of at most
156
+ # BODY_BYTES, JSON objects only. Each fetch is ctx.http's one log line
157
+ # (no query, no body); its failure a Refusal naming the origin.
158
+ class Wire
159
+ # @param http [#stream] ctx.http
160
+ # @param local [Boolean] the server's url is on a loopback host
161
+ # @param cancel [Samagotchi::CancellationController]
162
+ # @param resolve [#call] (host) → its addresses, for the internal check
163
+ # @param trusted [Array<String>] hosts the user configured (the
164
+ # server's url, oauth: issuer:): an internal address is theirs to
165
+ # choose; the guard is for what discovery names (https still)
166
+ def initialize(http:, local:, cancel:, resolve: nil, trusted: [])
167
+ @http = http
168
+ @local = local
169
+ @cancel = cancel
170
+ @trusted = trusted.compact.map { |host| host.to_s.downcase }
171
+ @resolve = resolve || ->(host) { Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address).uniq }
172
+ end
173
+
174
+ # @raise [Refusal] +url+ can't be asked for sign-in data
175
+ def check!(url, what)
176
+ uri = URI.parse(url.to_s)
177
+ raise Refusal, "#{what} isn't an address" unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? && uri.userinfo.nil?
178
+ raise Refusal, "#{what} isn't https (#{OAuth.origin(url)})" unless uri.scheme == "https" || (@local && OAuth.loopback_host?(uri.host))
179
+ return if @local || @trusted.include?(uri.host.to_s.downcase)
180
+
181
+ raise Refusal, "#{what} is an internal address (#{OAuth.origin(url)})" if internal?(uri.host)
182
+ rescue URI::Error
183
+ raise Refusal, "#{what} isn't an address"
184
+ end
185
+
186
+ # GET a JSON object.
187
+ # @return [Hash, nil] nil for a status that isn't 2xx (a 3xx too)
188
+ # @raise [Refusal] unreachable, too large, not a JSON object
189
+ def get_json(url, what)
190
+ check!(url, what)
191
+ status, body = fetch("GET", url, nil, { "Accept" => "application/json" }, FETCH_TIMEOUT, what)
192
+ return nil unless status.between?(200, 299)
193
+
194
+ object(body, what)
195
+ end
196
+
197
+ # POST a body; the answer's status and its JSON object (nil when it
198
+ # isn't one: an error page).
199
+ # @return [Array(Integer, Hash, nil)]
200
+ def post(url, body, content_type, what, timeout: FETCH_TIMEOUT)
201
+ check!(url, what)
202
+ headers = { "Accept" => "application/json", "Content-Type" => content_type }
203
+ status, text = fetch("POST", url, body, headers, timeout, what)
204
+ json = begin
205
+ object(text, what)
206
+ rescue Refusal
207
+ nil
208
+ end
209
+ [status, json]
210
+ end
211
+
212
+ # The status, and the body read up to BODY_BYTES (nil for a 3xx: not
213
+ # followed, not read).
214
+ def fetch(method, url, body, headers, timeout, what)
215
+ @http.stream(method, url, body: body, headers: headers, timeout: timeout, cancel: @cancel) do |res|
216
+ next [res.status, nil] if res.status.between?(300, 399)
217
+
218
+ text = +"".b
219
+ res.each_chunk do |bytes|
220
+ text << bytes
221
+ raise Refusal, "#{what} is larger than #{BODY_BYTES / 1024} KB" if text.bytesize > BODY_BYTES
222
+ end
223
+ [res.status, text]
224
+ end
225
+ rescue Samagotchi::Plugin::HttpCancelled
226
+ raise Refusal, "the sign-in was cancelled"
227
+ rescue Samagotchi::Plugin::HttpError
228
+ raise Refusal, "#{what} can't be reached (#{OAuth.origin(url)})"
229
+ end
230
+
231
+ private
232
+
233
+ def object(text, what)
234
+ value = JSON.parse(text.to_s.dup.force_encoding(Encoding::UTF_8))
235
+ raise Refusal, "#{what} isn't a JSON object" unless value.is_a?(Hash)
236
+
237
+ value
238
+ rescue JSON::ParserError, EncodingError
239
+ raise Refusal, "#{what} isn't a JSON object"
240
+ end
241
+
242
+ def internal?(host)
243
+ bare = host.delete_prefix("[").delete_suffix("]")
244
+ addresses = begin
245
+ [IPAddr.new(bare)]
246
+ rescue IPAddr::InvalidAddressError
247
+ Array(@resolve.call(bare)).filter_map { |ip| IPAddr.new(ip.to_s.sub(/%.*\z/, "")) rescue nil } # degrade-ok: a scoped address
248
+ end
249
+ addresses.any? { |ip| INTERNAL.any? { |range| range.include?(ip.ipv4_mapped? ? ip.native : ip) } }
250
+ rescue SocketError
251
+ false # a name that doesn't resolve: the fetch fails on its own
252
+ end
253
+ end
254
+
255
+ # The protected resource metadata, then its provider's (the spec's
256
+ # discovery), checked. +name+ is the server's (each refusal names it).
257
+ class Discovery
258
+ def initialize(wire:, name:, resource:)
259
+ @wire = wire
260
+ @name = name
261
+ @resource = resource
262
+ end
263
+
264
+ # @param challenge [Hash] the 401's Bearer parameters (OAuth.challenge)
265
+ # @param scopes [Array<String>, nil] oauth: scopes: from config
266
+ # @param bound [String, nil] the issuer a client registered by hand is
267
+ # for: another one is refused before it is asked anything (it would
268
+ # get the client's secret)
269
+ # @return [Provider]
270
+ # @raise [Refusal]
271
+ def run(challenge, scopes: nil, bound: nil)
272
+ resource = resource_metadata(challenge["resource_metadata"])
273
+ issuer = Array(resource["authorization_servers"]).first
274
+ raise Refusal, "#{@name}'s sign-in data names no sign-in provider" unless issuer.is_a?(String) && !issuer.empty?
275
+ if bound && issuer != bound
276
+ raise Refusal, "#{@name} now points at another sign-in provider (#{OAuth.plain(issuer, 200)}); your client is " \
277
+ "registered with #{bound}"
278
+ end
279
+
280
+ meta = provider_metadata(issuer)
281
+ scope = if scopes && !scopes.empty? then scopes.join(" ")
282
+ elsif challenge["scope"].to_s.strip != "" then challenge["scope"].strip
283
+ elsif resource["scopes_supported"].is_a?(Array) && !resource["scopes_supported"].empty?
284
+ resource["scopes_supported"].grep(String).join(" ")
285
+ end
286
+ Provider.new(issuer: issuer, authorization_endpoint: meta["authorization_endpoint"], token_endpoint: meta["token_endpoint"],
287
+ registration_endpoint: meta["registration_endpoint"], revocation_endpoint: meta["revocation_endpoint"],
288
+ iss_required: meta["authorization_response_iss_parameter_supported"] == true,
289
+ cimd: meta["client_id_metadata_document_supported"] == true, scope: scope)
290
+ end
291
+
292
+ # The well-known addresses of +url+'s protected resource metadata: the
293
+ # path inserted (its query and a trailing slash dropped), then the
294
+ # root (RFC 9728 §3.1).
295
+ def self.resource_addresses(url)
296
+ uri = URI.parse(url)
297
+ port = uri.port == uri.default_port ? "" : ":#{uri.port}"
298
+ origin = "#{uri.scheme}://#{uri.host}#{port}"
299
+ path = uri.path.to_s.sub(%r{/+\z}, "")
300
+ root = "#{origin}/.well-known/oauth-protected-resource"
301
+ path.empty? ? [root] : ["#{root}#{path}", root]
302
+ end
303
+
304
+ # The provider metadata addresses for +issuer+, in the spec's order.
305
+ def self.provider_addresses(issuer)
306
+ uri = URI.parse(issuer)
307
+ port = uri.port == uri.default_port ? "" : ":#{uri.port}"
308
+ origin = "#{uri.scheme}://#{uri.host}#{port}"
309
+ path = uri.path.to_s.sub(%r{/+\z}, "")
310
+ return ["#{origin}/.well-known/oauth-authorization-server", "#{origin}/.well-known/openid-configuration"] if path.empty?
311
+
312
+ ["#{origin}/.well-known/oauth-authorization-server#{path}", "#{origin}/.well-known/openid-configuration#{path}",
313
+ "#{origin}#{path}/.well-known/openid-configuration"]
314
+ end
315
+
316
+ private
317
+
318
+ # The header's address (the spec: use it when there is one), else the
319
+ # well-known ones in order; its resource must be this server's.
320
+ def resource_metadata(given)
321
+ addresses = given ? [given] : self.class.resource_addresses(@resource)
322
+ found = addresses.lazy.filter_map { |address| @wire.get_json(address, "#{@name}'s sign-in data") }.first
323
+ raise Refusal, "#{@name} asks for sign-in but gives no sign-in data (#{OAuth.origin(@resource)})" unless found
324
+ raise Refusal, "#{@name}'s sign-in data is for another address" unless OAuth.canonical(found["resource"]) == @resource
325
+
326
+ found
327
+ end
328
+
329
+ def provider_metadata(issuer)
330
+ @wire.check!(issuer, "#{@name}'s sign-in provider")
331
+ addresses = self.class.provider_addresses(issuer)
332
+ meta = addresses.lazy.filter_map { |address| @wire.get_json(address, "#{@name}'s provider metadata") }.first
333
+ raise Refusal, "#{@name}'s sign-in provider gives no metadata (#{OAuth.origin(issuer)})" unless meta
334
+ raise Refusal, "#{@name}'s provider metadata is for another provider" unless meta["issuer"] == issuer
335
+ unless Array(meta["code_challenge_methods_supported"]).include?("S256")
336
+ raise Refusal, "#{@name}'s sign-in provider doesn't offer PKCE (S256): chi can't sign in there"
337
+ end
338
+ unless meta["authorization_endpoint"].is_a?(String) && meta["token_endpoint"].is_a?(String)
339
+ raise Refusal, "#{@name}'s provider metadata has no authorization or token endpoint"
340
+ end
341
+
342
+ { "authorization_endpoint" => "authorization endpoint", "token_endpoint" => "token endpoint",
343
+ "registration_endpoint" => "registration endpoint", "revocation_endpoint" => "revocation endpoint" }.each do |key, what|
344
+ @wire.check!(meta[key], "#{@name}'s #{what}") if meta.key?(key)
345
+ end
346
+ meta
347
+ end
348
+ end
349
+
350
+ # One /mcp login's work, on the plugin's thread: discovery, the client,
351
+ # the flow (ctx.sign_in), the callback's checks and the exchange. Its
352
+ # #run keeps the token and returns the flow's card id.
353
+ class Login
354
+ # @param ctx [Plugin::Context] the plugin's (sign_in, http, secrets)
355
+ # @param server [Plugin::Server] a url server that signs in
356
+ # @param secret_lookup [#call] (variable) → its value, nil when unset
357
+ # @param client_metadata_url [String, nil] chi's CIMD address
358
+ # @param cimd_refused [Hash] issuer => true: the worker's providers
359
+ # that refused it (DCR from then on, never saved)
360
+ # @param cancel [Samagotchi::CancellationController] the plugin's
361
+ # sign-ins' (its shutdown)
362
+ # @param resolve [#call, nil] Wire's resolver (a spec's)
363
+ def initialize(ctx:, server:, secret_lookup:, client_metadata_url:, cimd_refused:, cancel:, log:, resolve: nil)
364
+ @ctx = ctx
365
+ @name = server.name
366
+ @url = server.url
367
+ @headers = server.headers || {}
368
+ @oauth = server.oauth.is_a?(Hash) ? server.oauth : {}
369
+ @resource = OAuth.canonical(@url)
370
+ @secret_lookup = secret_lookup
371
+ @client_metadata_url = client_metadata_url
372
+ @cimd_refused = cimd_refused
373
+ @cancel = cancel
374
+ @log = log
375
+ local = OAuth.loopback_host?(URI.parse(@url).host)
376
+ issuer_host = @oauth["client_id"] && URI.parse(@oauth["issuer"].to_s).host
377
+ @wire = Wire.new(http: ctx.http, local: local, cancel: cancel, resolve: resolve, trusted: [URI.parse(@url).host, issuer_host])
378
+ end
379
+
380
+ def inspect = "#<Login #{@name}>"
381
+
382
+ # @return [String, nil] the flow's card id once signed in; nil when the
383
+ # flow ended without a callback (core replaced its card)
384
+ # @raise [Refusal] (its card_id the flow's when there was one)
385
+ def run
386
+ provider = Discovery.new(wire: @wire, name: @name, resource: @resource)
387
+ .run(probe, scopes: Array(@oauth["scopes"]).grep(String), bound: @oauth["client_id"] && @oauth["issuer"])
388
+ registration = client_for(provider)
389
+ begin
390
+ attempt(provider, registration)
391
+ rescue InvalidClient => e
392
+ raise if registration.fresh || registration.kind == :config
393
+
394
+ @cimd_refused[provider.issuer] = true if registration.kind == :cimd
395
+ @ctx.card(id: e.card_id, title: "Signing in to #{@name} again", body: "The provider didn't know chi's client: " \
396
+ "chi registers again; open the new sign-in.", between_turns: true)
397
+ attempt(provider, client_for(provider, fresh: true))
398
+ end
399
+ end
400
+
401
+ private
402
+
403
+ # One request with no token, for the 401's challenge (the plugin's
404
+ # client threw it away): {} when it has none.
405
+ def probe
406
+ @wire.check!(@url, "#{@name}'s address") unless OAuth.loopback_host?(URI.parse(@url).host)
407
+ body = JSON.generate({ jsonrpc: "2.0", id: 0, method: "server/discover", params: {} })
408
+ headers = @headers.merge("Accept" => HttpClient::ACCEPT, "Content-Type" => "application/json",
409
+ "MCP-Protocol-Version" => HttpClient::MODERN, "Mcp-Method" => "server/discover")
410
+ @ctx.http.stream("POST", @url, body: body, headers: headers, timeout: FETCH_TIMEOUT, cancel: @cancel) do |res|
411
+ res.status == 401 ? OAuth.challenge(res.headers["www-authenticate"]) : {}
412
+ end
413
+ rescue Samagotchi::Plugin::HttpCancelled
414
+ raise Refusal, "the sign-in was cancelled"
415
+ rescue Samagotchi::Plugin::HttpError
416
+ raise Refusal, "#{@name} can't be reached (#{OAuth.origin(@url)})"
417
+ end
418
+
419
+ # The client, in the spec's order: configured, chi's document (CIMD),
420
+ # a registration of chi's own (DCR, kept per provider), else none.
421
+ def client_for(provider, fresh: false)
422
+ port = @oauth["redirect_port"]
423
+ if (id = @oauth["client_id"])
424
+ return configured(provider, id, port)
425
+ end
426
+ if !fresh && provider.cimd && @client_metadata_url && !@cimd_refused[provider.issuer]
427
+ return Registration.new(kind: :cimd, client_id: @client_metadata_url, client_secret: nil, port: port, fresh: false)
428
+ end
429
+ return registered(provider, port, fresh) if provider.registration_endpoint
430
+
431
+ raise Refusal, "#{@name}'s sign-in provider needs a client you register yourself: set oauth: client_id: and issuer: " \
432
+ "(and redirect_port: when it wants one exact redirect address)"
433
+ end
434
+
435
+ # A client registered by hand (bound to its provider: Discovery#run).
436
+ def configured(_provider, id, port)
437
+ secret = nil
438
+ if (variable = @oauth["client_secret_env"])
439
+ secret = @secret_lookup.call(variable)
440
+ raise Refusal, "#{variable} is not set (oauth: client_secret_env:)" if secret.nil? || secret.empty?
441
+ end
442
+ Registration.new(kind: :config, client_id: id, client_secret: secret, port: port, fresh: false)
443
+ end
444
+
445
+ # chi's registration with the provider: the kept one for the redirect
446
+ # port it was made for, else a new one (RFC 7591), kept.
447
+ def registered(provider, port, fresh)
448
+ name = OAuth.client_name(provider.issuer)
449
+ kept = fresh ? nil : parse(@ctx.secrets.get(name))
450
+ kept = nil if kept && (kept["issuer"] != provider.issuer || (port && kept["port"] != port))
451
+ if kept
452
+ return Registration.new(kind: :dcr, client_id: kept["client_id"], client_secret: kept["client_secret"],
453
+ port: kept["port"], fresh: false)
454
+ end
455
+
456
+ port ||= free_port
457
+ redirect = "http://127.0.0.1:#{port}/callback"
458
+ body = { client_name: "chi", redirect_uris: [LOOPBACK_REDIRECT, redirect], application_type: "native",
459
+ grant_types: %w[authorization_code refresh_token], response_types: ["code"], token_endpoint_auth_method: "none" }
460
+ status, answer = @wire.post(provider.registration_endpoint, JSON.generate(body), "application/json",
461
+ "#{@name}'s provider's registration")
462
+ unless status.between?(200, 299) && answer && answer["client_id"].is_a?(String) && !answer["client_id"].empty?
463
+ raise Refusal, "#{@name}'s sign-in provider didn't register chi (#{error_of(status, answer)})"
464
+ end
465
+
466
+ secret = answer["client_secret"].is_a?(String) ? answer["client_secret"] : nil
467
+ @ctx.secrets.set(name, JSON.generate({ client_id: answer["client_id"], client_secret: secret, port: port,
468
+ redirect_uri: redirect, issuer: provider.issuer }.compact))
469
+ @log.call("oauth_registered", server: @name, provider: OAuth.origin(provider.issuer))
470
+ Registration.new(kind: :dcr, client_id: answer["client_id"], client_secret: secret, port: port, fresh: true)
471
+ end
472
+
473
+ # The flow: the authorize address built inside ctx.sign_in's block, the
474
+ # callback checked, the code exchanged, the token kept.
475
+ def attempt(provider, registration)
476
+ verifier = [SecureRandom.random_bytes(64)].pack("m0").tr("+/", "-_").delete("=")
477
+ state = [SecureRandom.random_bytes(32)].pack("m0").tr("+/", "-_").delete("=")
478
+ flow = begin
479
+ @ctx.sign_in(title: "Sign in to #{@name}", button: "Open sign-in page", timeout: SIGN_IN_TIMEOUT,
480
+ port: registration.port, cancel: @cancel) do |redirect_uri|
481
+ authorize_address(provider, registration, redirect_uri, verifier, state)
482
+ end
483
+ rescue ArgumentError => e
484
+ raise unless e.message.match?(/port \d+ is taken/)
485
+
486
+ raise Refusal, "port #{registration.port} is in use: try again, or set oauth: redirect_port:"
487
+ end
488
+ return nil if flow.outcome == :stopped
489
+
490
+ result = flow.wait
491
+ return nil unless result
492
+
493
+ with_card(flow.card_id) do
494
+ code = callback_code(result, provider, state)
495
+ record = exchange(provider, registration, code, verifier, flow.redirect_uri)
496
+ @ctx.secrets.set(OAuth.token_name(@resource), JSON.generate(record))
497
+ @log.call("oauth_signed_in", server: @name, provider: OAuth.origin(provider.issuer), expires: !record[:expires_at].nil?)
498
+ end
499
+ flow.card_id
500
+ end
501
+
502
+ def with_card(card_id)
503
+ yield
504
+ rescue Refusal => e
505
+ e.card_id ||= card_id
506
+ raise
507
+ end
508
+
509
+ def authorize_address(provider, registration, redirect_uri, verifier, state)
510
+ params = { response_type: "code", client_id: registration.client_id, redirect_uri: redirect_uri, state: state,
511
+ code_challenge: [Digest::SHA256.digest(verifier)].pack("m0").tr("+/", "-_").delete("="),
512
+ code_challenge_method: "S256", resource: @resource, scope: provider.scope }.compact
513
+ uri = URI.parse(provider.authorization_endpoint)
514
+ uri.query = [uri.query, URI.encode_www_form(params)].compact.join("&")
515
+ uri.to_s
516
+ end
517
+
518
+ # The callback's code, after its checks (RFC 9207's iss first: on a
519
+ # mismatch the error isn't shown).
520
+ def callback_code(result, provider, state)
521
+ iss = result["iss"]
522
+ raise Refusal, "the sign-in answer came from another provider" if iss && iss != provider.issuer
523
+ raise Refusal, "the sign-in answer doesn't name its provider (iss)" if iss.nil? && provider.iss_required
524
+
525
+ # Core checked it too (ctx.sign_in): again here, in constant time.
526
+ raise Refusal, "the sign-in answer's state doesn't match" unless OpenSSL.secure_compare(result["state"].to_s, state)
527
+
528
+ if result["error"]
529
+ error = OAuth.plain(result["error"], 64)
530
+ raise InvalidClient, "#{@name}'s provider refused chi's client (invalid_client)" if error == "invalid_client"
531
+
532
+ detail = OAuth.plain(result["error_description"], 200)
533
+ raise Refusal, "the provider refused: #{error}#{": #{detail}" unless detail.empty?}"
534
+ end
535
+ code = result["code"].to_s
536
+ raise Refusal, "the sign-in answer has no code" if code.empty?
537
+
538
+ code
539
+ end
540
+
541
+ # The code for a token (RFC 6749 §4.1.3, PKCE's verifier, RFC 8707's
542
+ # resource), kept as one JSON value bound to this url.
543
+ def exchange(provider, registration, code, verifier, redirect_uri)
544
+ form = { grant_type: "authorization_code", code: code, redirect_uri: redirect_uri, client_id: registration.client_id,
545
+ code_verifier: verifier, resource: @resource, client_secret: registration.client_secret }.compact
546
+ status, answer = @wire.post(provider.token_endpoint, URI.encode_www_form(form), "application/x-www-form-urlencoded",
547
+ "#{@name}'s token endpoint", timeout: EXCHANGE_TIMEOUT)
548
+ unless status.between?(200, 299)
549
+ error = error_of(status, answer)
550
+ raise InvalidClient, "#{@name}'s provider refused chi's client (invalid_client)" if error == "invalid_client"
551
+
552
+ raise Refusal, "#{@name}'s sign-in provider gave no token (#{error})"
553
+ end
554
+ token = answer && answer["access_token"]
555
+ unless token.is_a?(String) && !token.empty? && answer["token_type"].to_s.casecmp?("bearer")
556
+ raise Refusal, "#{@name}'s sign-in provider's answer has no bearer token"
557
+ end
558
+
559
+ Token.record(answer, provider: provider, registration: registration, resource: @resource)
560
+ end
561
+
562
+ # A provider's OAuth error code, or the status.
563
+ def error_of(status, answer)
564
+ code = answer.is_a?(Hash) ? OAuth.plain(answer["error"], 64) : ""
565
+ code.empty? ? "HTTP #{status}" : code
566
+ end
567
+
568
+ def parse(text)
569
+ value = text && JSON.parse(text)
570
+ value.is_a?(Hash) ? value : nil
571
+ rescue JSON::ParserError
572
+ nil
573
+ end
574
+
575
+ # A port free now on 127.0.0.1, for a registration's exact redirect.
576
+ def free_port
577
+ server = TCPServer.new("127.0.0.1", 0)
578
+ server.addr[1]
579
+ ensure
580
+ server&.close
581
+ end
582
+ end
583
+
584
+ # The token HttpClient sends for a server that signs in (its token:,
585
+ # beside StaticToken): the kept sign-in for this url (ctx.secrets,
586
+ # OAuth.token_name), read once per worker into memory and again while
587
+ # there is none. A kept token whose resource isn't this url is never
588
+ # sent. It renews itself when it runs out within AHEAD seconds, and on
589
+ # HttpClient's 401 (#refresh_token!). Safe from several threads: one
590
+ # Mutex over what it holds, one more so a worker renews once at a time;
591
+ # across workers, the secret's lock.
592
+ class Token
593
+ # Renewed when it runs out within this many seconds (or half its life,
594
+ # if that is shorter: a token for a minute isn't renewed at each request).
595
+ AHEAD = 60
596
+ # The renew request's whole time (by the clock, its own controller:
597
+ # never the turn's, a Stop would lose a rotated refresh token) and the
598
+ # wait for another worker's renew: above that request's, and at most
599
+ # 30 s together, outside the call's own timeout.
600
+ RENEW_SECONDS = 12
601
+ RENEW_LOCK = 18
602
+
603
+ # The JSON value kept for a sign-in.
604
+ def self.record(answer, provider:, registration:, resource:, now: Time.now.to_i)
605
+ expires_in = Integer(answer["expires_in"], exception: false) if answer.key?("expires_in")
606
+ { access_token: answer["access_token"],
607
+ refresh_token: answer["refresh_token"].is_a?(String) ? answer["refresh_token"] : nil,
608
+ expires_at: expires_in&.positive? ? now + expires_in : nil, issued_at: now,
609
+ scope: answer["scope"].is_a?(String) ? answer["scope"] : provider.scope,
610
+ issuer: provider.issuer, token_endpoint: provider.token_endpoint, revocation_endpoint: provider.revocation_endpoint,
611
+ client_id: registration.client_id, client_secret: registration.kind == :dcr ? registration.client_secret : nil,
612
+ resource: resource }.compact
613
+ end
614
+
615
+ # @param secrets [#get, #update, #delete] ctx.secrets
616
+ # @param resource [String, nil] the server's canonical url (nil: one
617
+ # that can't sign in, a url with a query: never a token)
618
+ # @param http [#stream, nil] ctx.http, for renewing (nil: never renews)
619
+ # @param client [Hash, nil] the configured client ({id:, issuer:}):
620
+ # its secret goes only with a kept sign-in made as that client at that
621
+ # provider, never to another one's token endpoint
622
+ # @param client_secret [#call] → the configured client's secret, nil
623
+ # @param log [#call] (event, fields)
624
+ # @param clock [#call] → now, epoch seconds
625
+ def initialize(secrets:, resource:, http: nil, client: nil, client_secret: -> {}, log: ->(*) {}, clock: -> { Time.now.to_i })
626
+ @secrets = secrets
627
+ @resource = resource
628
+ @client = client
629
+ @name = resource && OAuth.token_name(resource)
630
+ @http = http
631
+ @client_secret = client_secret
632
+ @log = log
633
+ @clock = clock
634
+ @mutex = Mutex.new
635
+ @renewing = Mutex.new
636
+ @held = nil
637
+ end
638
+
639
+ def inspect = "#<OAuth::Token #{@resource ? OAuth.origin(@resource) : "none"} held=#{!@held.nil?}>"
640
+
641
+ def pretty_print(printer) = printer.text(inspect)
642
+
643
+ # The access token, renewed first when it runs out within AHEAD
644
+ # seconds (one that can't be renewed now is still sent while it holds).
645
+ # @return [String, nil] nil when there is no sign-in
646
+ # @raise [NeedsSignIn] renewing was refused; [Client::Dead] it failed
647
+ # and the token ran out; [Client::Unavailable] the store failed
648
+ def call
649
+ current = held
650
+ return nil unless current
651
+
652
+ expires_at = current["expires_at"]
653
+ if expires_at.is_a?(Integer) && expires_at - @clock.call < ahead(current) && current["refresh_token"] && @http
654
+ begin
655
+ refresh_token!(current["access_token"])
656
+ rescue NeedsSignIn
657
+ raise
658
+ rescue Client::Error
659
+ raise if expires_at <= @clock.call
660
+ end
661
+ current = held
662
+ end
663
+ current&.fetch("access_token")
664
+ end
665
+
666
+ # Renew the token +sent+ (the one a 401 refused; nil: the one held),
667
+ # under the secret's lock: another worker that renewed it already
668
+ # gave the store a newer token, taken with no request; else a
669
+ # refresh_token grant at the kept token endpoint, the new token kept
670
+ # (and the new refresh token, else the old).
671
+ # @return [Boolean] true: a new token to try
672
+ # @raise [NeedsSignIn] no refresh token, or the provider refused it
673
+ # (invalid_grant): the kept sign-in is deleted; [Client::Dead] the
674
+ # provider can't be reached or failed: the token is kept
675
+ def refresh_token!(sent = nil)
676
+ return false unless @name && @http
677
+
678
+ @renewing.synchronize do
679
+ known = @mutex.synchronize { @held }
680
+ return true if sent && known && known["access_token"] != sent # this worker renewed it meanwhile
681
+
682
+ stale = sent || known&.fetch("access_token")
683
+ outcome = nil
684
+ @secrets.update(@name, timeout: RENEW_LOCK) do |old|
685
+ stored = parse(old)
686
+ if stored.nil? || stored["resource"] != @resource
687
+ outcome = :gone
688
+ next old
689
+ end
690
+ if stored["access_token"] != stale
691
+ outcome = :taken
692
+ @mutex.synchronize { @held = stored }
693
+ next old
694
+ end
695
+ outcome, value = renewed(stored)
696
+ next value
697
+ end
698
+ settle(outcome)
699
+ end
700
+ rescue Samagotchi::Plugin::Secrets::Unavailable, Samagotchi::Plugin::Secrets::Busy => e
701
+ raise Client::Unavailable, "the sign-in can't be renewed: #{e.message}"
702
+ rescue ArgumentError => e # a renewed sign-in the store refuses (over 16 KB): nothing kept, the old one stays
703
+ raise Client::Unavailable, "the sign-in can't be renewed: #{e.message[/\A[^(]{0,120}/].strip}"
704
+ end
705
+
706
+ # Forget what it holds: the next #call reads the store (a new sign-in,
707
+ # a sign-out).
708
+ def forget = @mutex.synchronize { @held = nil }
709
+
710
+ # The kept sign-in (for a sign-out's revocation), read now.
711
+ # @return [Hash, nil]
712
+ def kept = read
713
+
714
+ # The store's name for it (nil when it can't sign in).
715
+ attr_reader :name
716
+
717
+ private
718
+
719
+ def held
720
+ @mutex.synchronize { @held ||= read }
721
+ end
722
+
723
+ def ahead(record)
724
+ life = record["expires_at"] - record["issued_at"] if record["issued_at"].is_a?(Integer)
725
+ life ? [AHEAD, life / 2].min : AHEAD
726
+ end
727
+
728
+ def read
729
+ return nil unless @name
730
+
731
+ value = parse(@secrets.get(@name))
732
+ return nil unless value && value["resource"] == @resource
733
+
734
+ value
735
+ rescue Samagotchi::Plugin::Secrets::Unavailable, Samagotchi::Plugin::Secrets::Busy => e
736
+ raise Client::Unavailable, "the sign-in can't be read: #{e.message}"
737
+ end
738
+
739
+ def parse(text)
740
+ value = text && JSON.parse(text)
741
+ value.is_a?(Hash) && value["access_token"].is_a?(String) ? value : nil
742
+ rescue JSON::ParserError
743
+ nil
744
+ end
745
+
746
+ # Inside the secret's lock: the refresh_token grant.
747
+ # @return [Array(Symbol, String|nil)] the outcome and what the store keeps
748
+ def renewed(stored)
749
+ return [:refused, nil] unless stored["refresh_token"].is_a?(String)
750
+
751
+ status, answer = grant(stored)
752
+ if status.between?(200, 299) && answer && answer["access_token"].is_a?(String) &&
753
+ answer["token_type"].to_s.casecmp?("bearer")
754
+ expires_in = Integer(answer["expires_in"], exception: false)
755
+ fresh = stored.merge("access_token" => answer["access_token"],
756
+ "refresh_token" => answer["refresh_token"].is_a?(String) ? answer["refresh_token"] : stored["refresh_token"],
757
+ "expires_at" => expires_in&.positive? ? @clock.call + expires_in : nil, "issued_at" => @clock.call)
758
+ fresh["scope"] = answer["scope"] if answer["scope"].is_a?(String)
759
+ @mutex.synchronize { @held = fresh }
760
+ @log.call("oauth_renewed", where: OAuth.origin(stored["token_endpoint"]))
761
+ return [:renewed, JSON.generate(fresh)]
762
+ end
763
+ error = answer.is_a?(Hash) ? OAuth.plain(answer["error"], 64) : ""
764
+ @log.call("oauth_not_renewed", where: OAuth.origin(stored["token_endpoint"]), status: status, error: error)
765
+ return [:refused, nil] if error == "invalid_grant"
766
+
767
+ @failure = error.empty? ? "HTTP #{status}" : error
768
+ [:failed, JSON.generate(stored)]
769
+ rescue Refusal => e
770
+ @log.call("oauth_not_renewed", where: OAuth.origin(stored["token_endpoint"]), error: "unreachable")
771
+ @failure = e.message
772
+ [:failed, JSON.generate(stored)]
773
+ end
774
+
775
+ # The grant, on a controller of its own cancelled after RENEW_SECONDS.
776
+ def grant(stored)
777
+ form = { grant_type: "refresh_token", refresh_token: stored["refresh_token"], client_id: stored["client_id"],
778
+ resource: @resource, client_secret: stored["client_secret"] || configured_secret(stored) }.compact
779
+ cancel = Samagotchi::CancellationController.new
780
+ timer = Thread.new do
781
+ sleep(RENEW_SECONDS)
782
+ cancel.cancel!(:budget)
783
+ end
784
+ # The kept endpoint is checked again (an address can resolve elsewhere
785
+ # by now); the hosts the user configured are trusted, as at the sign-in.
786
+ local = OAuth.loopback_host?(URI.parse(@resource).host)
787
+ trusted = [URI.parse(@resource).host, @client && URI.parse(@client[:issuer].to_s).host]
788
+ Wire.new(http: @http, local: local, cancel: cancel, trusted: trusted)
789
+ .post(stored["token_endpoint"], URI.encode_www_form(form), "application/x-www-form-urlencoded",
790
+ "the token endpoint", timeout: RENEW_SECONDS)
791
+ ensure
792
+ timer&.kill&.join
793
+ end
794
+
795
+ # The configured client's secret, for a sign-in made as that client
796
+ # (its id and provider both): nil for any other.
797
+ def configured_secret(stored)
798
+ return nil unless @client && stored["client_id"] == @client[:id] && stored["issuer"] == @client[:issuer]
799
+
800
+ @client_secret.call
801
+ end
802
+
803
+ def settle(outcome)
804
+ case outcome
805
+ when :taken, :renewed then true
806
+ when :failed then raise Client::Dead, "its sign-in couldn't be renewed (#{@failure})"
807
+ else
808
+ forget
809
+ raise NeedsSignIn
810
+ end
811
+ end
812
+ end
813
+ end
814
+ end