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,266 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "monitor"
5
+ require_relative "../atomic_file"
6
+ require_relative "../paths"
7
+
8
+ module Samagotchi
9
+ module Plugin
10
+ # ctx.secrets (docs/plugins.md, Secrets): what a bundle keeps that must
11
+ # not sit in a plain data file, tokens. Per bundle: bundle mcp's "linear"
12
+ # and another bundle's "linear" are different secrets. A value is never
13
+ # logged, never in an exception's message, never in #inspect.
14
+ #
15
+ # Core never caches: #get reads the store each time; a bundle keeps the
16
+ # token in memory and reads again on a 401.
17
+ #
18
+ # The store is FileStore everywhere: one 0600 file per secret in a 0700
19
+ # folder under the state dir. The login Keychain was tried and left out
20
+ # (plan 3's B0, 2026-11-21): `security` takes a value without it showing
21
+ # in an argument list only through `security -i` on stdin, whose line is
22
+ # cut at about 4 KB and ends at a newline, and its prompt keeps 128
23
+ # characters.
24
+ class Secrets
25
+ # The store can't be reached (disk, permissions). The message names
26
+ # the store and the secret's name only.
27
+ class Unavailable < StandardError; end
28
+
29
+ # Another holder (another worker refreshing the same token) kept the
30
+ # secret's lock past the deadline.
31
+ class Busy < StandardError; end
32
+
33
+ # A name never starts with a dot (the lock folder is .locks) nor ends
34
+ # in .tmp (AtomicFile's temp files beside the values).
35
+ NAME = /\A(?!.*\.tmp\z)[a-z0-9][a-z0-9._-]{0,63}\z/
36
+ # The secrets this thread holds the lock of now (#locked).
37
+ HELD = :samagotchi_secrets_held
38
+ MAX_BYTES = 16 * 1024
39
+ LOCK_TIMEOUT = 30
40
+
41
+ # @param store [FileStore, MemoryStore] the bundle's own
42
+ def initialize(store)
43
+ @store = store
44
+ end
45
+
46
+ def inspect = "#<#{self.class.name} backend=#{backend}>"
47
+
48
+ def pretty_print(printer) = printer.text(inspect)
49
+
50
+ # @return [Symbol] :file (or :memory in the bundle test kit), for a
51
+ # bundle's status line
52
+ def backend = @store.backend
53
+
54
+ # @return [String, nil] the value, nil when there is none
55
+ # @raise [ArgumentError] a bad name; [Unavailable]
56
+ def get(name)
57
+ @store.read(check_name(name))
58
+ end
59
+
60
+ # @return [true]
61
+ # @raise [ArgumentError] a bad name or value; [Unavailable]; [Busy]
62
+ def set(name, value, timeout: LOCK_TIMEOUT)
63
+ name = check_name(name)
64
+ value = check_value(value)
65
+ locked(name, timeout) { @store.write(name, value) }
66
+ true
67
+ end
68
+
69
+ # @return [Boolean] whether there was one
70
+ def delete(name, timeout: LOCK_TIMEOUT)
71
+ name = check_name(name)
72
+ locked(name, timeout) { @store.remove(name) }
73
+ end
74
+
75
+ # Read, change, write under the secret's lock (two workers refreshing
76
+ # the same token don't each spend the refresh token: the second one's
77
+ # block gets the first one's new value). The block gets the value now
78
+ # (nil for none) and returns the new one; nil deletes it.
79
+ # @return [String, nil] what the secret holds after
80
+ # @raise [ArgumentError] a bad name, or a block's bad value (nothing
81
+ # is written then); [Unavailable]; [Busy] past +timeout+ seconds
82
+ def update(name, timeout: LOCK_TIMEOUT)
83
+ raise ArgumentError, "ctx.secrets.update needs a block" unless block_given?
84
+
85
+ name = check_name(name)
86
+ locked(name, timeout) do
87
+ value = yield @store.read(name)
88
+ if value.nil?
89
+ @store.remove(name)
90
+ next nil
91
+ end
92
+
93
+ @store.write(name, check_value(value))
94
+ value
95
+ end
96
+ end
97
+
98
+ private
99
+
100
+ # The store's lock on +name+; refused at once when this thread holds
101
+ # it already (a set, delete or update inside the secret's own update
102
+ # block would wait for itself: a file lock taken again by the same
103
+ # process conflicts, and the wait would end in Busy).
104
+ def locked(name, timeout, &)
105
+ key = @store.lock_key(name)
106
+ held = (Thread.current[HELD] ||= [])
107
+ if held.include?(key)
108
+ raise ArgumentError, "secret #{name} is held by this thread already (inside its own update block): " \
109
+ "return the new value from the block instead"
110
+ end
111
+
112
+ held << key
113
+ begin
114
+ @store.locked(name, timeout: timeout, &)
115
+ ensure
116
+ held.delete(key)
117
+ end
118
+ end
119
+
120
+ def check_name(name)
121
+ name = name.to_s if name.is_a?(Symbol)
122
+ unless name.is_a?(String) && name.match?(NAME)
123
+ raise ArgumentError, "a secret's name is a String like \"linear\" (a-z 0-9 . _ -, 1..64, a letter or digit first, " \
124
+ "not ending .tmp)"
125
+ end
126
+
127
+ name
128
+ end
129
+
130
+ # Never the value in the message.
131
+ def check_value(value)
132
+ raise ArgumentError, "a secret's value is a String (encode JSON yourself)" unless value.is_a?(String)
133
+ raise ArgumentError, "a secret's value is at most #{MAX_BYTES} bytes" if value.bytesize > MAX_BYTES
134
+
135
+ value
136
+ end
137
+
138
+ # One file per secret, <state dir>/plugins/<bundle>/secrets/<name>,
139
+ # 0600 in a 0700 folder, written whole (AtomicFile). Its lock is
140
+ # .locks/<name> under that folder (no secret's name starts with a
141
+ # dot), an exclusive flock held across processes.
142
+ class FileStore
143
+ POLL = 0.02
144
+ LOCKS = ".locks"
145
+
146
+ # @param dir [String] the bundle's secrets folder
147
+ # @param clock [#call] monotonic seconds (specs pass their own)
148
+ # @param wait [#call] waits +seconds+ between lock tries
149
+ def initialize(dir, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, wait: ->(seconds) { sleep(seconds) })
150
+ @dir = dir
151
+ @clock = clock
152
+ @wait = wait
153
+ end
154
+
155
+ # @param bundle [String]
156
+ def self.for_bundle(bundle, env: ENV)
157
+ new(File.join(Paths.state_dir(env: env), "plugins", bundle.to_s, "secrets"))
158
+ end
159
+
160
+ def backend = :file
161
+
162
+ def inspect = "#<#{self.class.name}>"
163
+
164
+ # What one thread's held locks are told apart by: the lock file.
165
+ def lock_key(name) = File.expand_path(lock_path(name))
166
+
167
+ def read(name)
168
+ File.binread(path(name)).force_encoding(Encoding::UTF_8)
169
+ rescue Errno::ENOENT
170
+ nil
171
+ rescue SystemCallError, IOError
172
+ raise Unavailable, "the secrets folder can't be read (secret #{name})"
173
+ end
174
+
175
+ def write(name, value)
176
+ folder
177
+ AtomicFile.write(path(name), value, perm: 0o600)
178
+ rescue SystemCallError, IOError
179
+ raise Unavailable, "the secrets folder can't be written (secret #{name})"
180
+ end
181
+
182
+ def remove(name)
183
+ File.delete(path(name))
184
+ true
185
+ rescue Errno::ENOENT
186
+ false
187
+ rescue SystemCallError
188
+ raise Unavailable, "the secrets folder can't be written (secret #{name})"
189
+ end
190
+
191
+ # @raise [Busy] the lock still held after +timeout+ seconds
192
+ def locked(name, timeout:)
193
+ lock = open_lock(name)
194
+ begin
195
+ take(lock, name, timeout)
196
+ yield
197
+ ensure
198
+ lock.close
199
+ end
200
+ end
201
+
202
+ private
203
+
204
+ def path(name) = File.join(@dir, name)
205
+
206
+ def lock_path(name) = File.join(@dir, LOCKS, name)
207
+
208
+ def folder
209
+ FileUtils.mkdir_p(@dir, mode: 0o700)
210
+ File.chmod(0o700, @dir)
211
+ end
212
+
213
+ def open_lock(name)
214
+ folder
215
+ locks = File.join(@dir, LOCKS)
216
+ FileUtils.mkdir_p(locks, mode: 0o700)
217
+ File.chmod(0o700, locks)
218
+ File.open(lock_path(name), File::RDWR | File::CREAT, 0o600)
219
+ rescue SystemCallError, IOError
220
+ raise Unavailable, "the secrets folder can't be locked (secret #{name})"
221
+ end
222
+
223
+ def take(lock, name, timeout)
224
+ deadline = @clock.call + timeout
225
+ until lock.flock(File::LOCK_EX | File::LOCK_NB)
226
+ raise Busy, "secret #{name} is held by another process (waited #{timeout} s)" if @clock.call >= deadline
227
+
228
+ @wait.call(POLL)
229
+ end
230
+ end
231
+ end
232
+
233
+ # The bundle test kit's store: a Hash, never a disk or a Keychain.
234
+ # bundle.secrets reads it, bundle.set(secrets: {...}) seeds it.
235
+ class MemoryStore
236
+ def initialize(values = {})
237
+ @values = values
238
+ @mutex = Monitor.new
239
+ end
240
+
241
+ def backend = :memory
242
+
243
+ def inspect = "#<#{self.class.name}>"
244
+
245
+ def to_h = @mutex.synchronize { @values.dup }
246
+
247
+ # @param values [Hash] name => value, what the store then holds
248
+ def replace(values)
249
+ @mutex.synchronize { @values = values.to_h { |name, value| [name.to_s, value.to_s.dup.freeze] } }
250
+ end
251
+
252
+ def read(name) = @mutex.synchronize { @values[name]&.dup }
253
+
254
+ def write(name, value)
255
+ @mutex.synchronize { @values[name] = value.dup.freeze }
256
+ end
257
+
258
+ def remove(name) = @mutex.synchronize { !@values.delete(name).nil? }
259
+
260
+ def lock_key(name) = [object_id, name]
261
+
262
+ def locked(_name, timeout:, &) = @mutex.synchronize(&)
263
+ end
264
+ end
265
+ end
266
+ end
@@ -0,0 +1,392 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "io/wait"
4
+ require "socket"
5
+ require "uri"
6
+ require_relative "../log"
7
+
8
+ module Samagotchi
9
+ module Plugin
10
+ # ctx.sign_in's flow (docs/plugins.md, Sign-in): send the session's owner
11
+ # to an address, get back the address the browser was sent to. Core
12
+ # knows nothing of OAuth beyond one check: the address the bundle builds
13
+ # must have a `state` query parameter (#started refuses one without: any
14
+ # local process or web page could finish it), and a callback whose
15
+ # `state` differs is ignored and the wait goes on.
16
+ #
17
+ # The browser comes back to a Listener on 127.0.0.1 (#redirect_uri), or
18
+ # the user pastes the address it ended on with /callback (#offer). The
19
+ # first callback that passes settles it :done; #wait returns its query.
20
+ # It also ends :timed_out (its deadline), :cancelled (#cancel, or the
21
+ # +cancel+ controller the bundle passed: a turn's Stop) or :stopped (the
22
+ # worker leaving, #stop): +on_settle+ hears each, once.
23
+ class SignIn
24
+ OUTCOMES = %i[done timed_out cancelled stopped].freeze
25
+ TIMEOUTS = (60..900)
26
+ DEFAULT_TIMEOUT = 300
27
+ DEFAULT_PATH = "/callback"
28
+ # How often a waiting thread or the listener looks at the deadline
29
+ # with nothing else to wake it, in seconds.
30
+ TICK = 1.0
31
+
32
+ # The card that replaces a flow's when it ends without a callback.
33
+ ENDED_TITLES = { timed_out: "Sign-in timed out", cancelled: "Sign-in cancelled", stopped: "Sign-in cancelled" }.freeze
34
+
35
+ # The card's line for a browser on another device.
36
+ PASTE_LINE = "If the browser ends on a page that doesn't load, copy that page's address and run " \
37
+ "`/callback <address>`."
38
+
39
+ attr_reader :title, :button, :card_id, :redirect_uri, :address, :bundle
40
+
41
+ # A flow that asks no one (a one-shot run, a stream hook's handler):
42
+ # already :stopped, no card, no port.
43
+ def self.stopped(bundle:, title:)
44
+ new(bundle: bundle, title: title, button: nil, timeout: DEFAULT_TIMEOUT, listener: nil).tap do |flow|
45
+ flow.instance_variable_set(:@outcome, :stopped)
46
+ end
47
+ end
48
+
49
+ # @raise [ArgumentError] a timeout outside TIMEOUTS, a bad path, a
50
+ # cancel: that isn't a controller
51
+ def self.check_options!(timeout:, path:, cancel: nil)
52
+ unless cancel.nil? || cancel.respond_to?(:cancelled?)
53
+ raise ArgumentError, "ctx.sign_in's cancel: is a Samagotchi::CancellationController (ctx.cancel_controller) or nil"
54
+ end
55
+ unless timeout.is_a?(Numeric) && TIMEOUTS.cover?(timeout)
56
+ raise ArgumentError, "ctx.sign_in's timeout: is #{TIMEOUTS.min}..#{TIMEOUTS.max} seconds"
57
+ end
58
+ return if path.is_a?(String) && path.match?(%r{\A/[A-Za-z0-9._~/-]*\z})
59
+
60
+ raise ArgumentError, "ctx.sign_in's path: is an absolute path like /callback"
61
+ end
62
+
63
+ # The fields of the card that replaces +flow+'s when it ended as
64
+ # +outcome+ without a callback; nil for :done (the bundle shows its
65
+ # result) or a flow with no card.
66
+ # @return [Hash, nil] Engine#show_card's keywords, the source left out
67
+ def self.ended_card(flow, outcome)
68
+ return nil if outcome == :done || flow.card_id.nil?
69
+
70
+ { id: flow.card_id, title: ENDED_TITLES.fetch(outcome), body: "#{flow.title}: run its command again to try again.",
71
+ actions: [] }
72
+ end
73
+
74
+ # @param listener [Listener, nil] bound already (the redirect_uri's port)
75
+ # @param redirect_uri [String, nil] without a listener (the test kit's)
76
+ # @param clock [#call] monotonic seconds
77
+ # @param on_settle [#call] (flow, outcome), once, off the lock
78
+ # @param cancel [CancellationController, nil] polled (each TICK, by
79
+ # the listener and any #wait): cancelled ends it :cancelled
80
+ def initialize(bundle:, title:, button:, timeout:, listener:, redirect_uri: nil,
81
+ clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, on_settle: nil, cancel: nil)
82
+ @bundle = bundle
83
+ @title = title
84
+ @button = button
85
+ @listener = listener
86
+ @clock = clock
87
+ @deadline = clock.call + timeout
88
+ @on_settle = on_settle
89
+ @cancel = cancel
90
+ @redirect_uri = listener&.redirect_uri || redirect_uri
91
+ @mutex = Mutex.new
92
+ @settled = ConditionVariable.new
93
+ @outcome = nil
94
+ @result = nil
95
+ end
96
+
97
+ # The flow's address, never its query (an authorize URL can carry a
98
+ # login hint).
99
+ def inspect = "#<#{self.class.name} bundle=#{@bundle} redirect_uri=#{@redirect_uri} outcome=#{outcome.inspect}>"
100
+
101
+ def pretty_print(printer) = printer.text(inspect)
102
+
103
+ # Set once, before the card shows (Engine#start_sign_in).
104
+ # @param address [String] the address the bundle built
105
+ # @param card_id [String]
106
+ # @raise [ArgumentError] the address has no state query parameter
107
+ def started(address, card_id)
108
+ state = state_of(address)
109
+ if state.nil? || state.empty?
110
+ raise ArgumentError, "ctx.sign_in's address needs a state query parameter (a random one per sign-in)"
111
+ end
112
+
113
+ @address = address
114
+ @state = state
115
+ @card_id = card_id
116
+ end
117
+
118
+ # The listener's thread starts: callbacks are taken from now. Should
119
+ # it fail, the flow ends :cancelled (its card says so).
120
+ def listen
121
+ @listener&.start(on_request: ->(query) { offer(query) }, on_tick: -> { expire_if_due },
122
+ on_failed: -> { settle(:cancelled) })
123
+ end
124
+
125
+ # @return [Symbol, nil] OUTCOMES, nil while it waits
126
+ def outcome = @mutex.synchronize { @outcome }
127
+
128
+ # Whether it still waits: past its deadline it ends now, whoever asks
129
+ # (nobody may be in #wait, and the listener may be gone).
130
+ def waiting?
131
+ expire_if_due
132
+ outcome.nil?
133
+ end
134
+
135
+ # Blocks until it settles (or +timeout+ seconds, when given, pass).
136
+ # @return [Hash, nil] the callback's query ({"code"=>…, "state"=>…}),
137
+ # nil for any other outcome
138
+ def wait(timeout = nil)
139
+ until_at = timeout && (@clock.call + timeout)
140
+ loop do
141
+ expire_if_due
142
+ @mutex.synchronize do
143
+ return @result unless @outcome.nil?
144
+
145
+ now = @clock.call
146
+ return nil if until_at && now >= until_at
147
+
148
+ left = [@deadline, until_at].compact.min - now
149
+ @settled.wait(@mutex, left.clamp(0.001, TICK))
150
+ return @result unless @outcome.nil?
151
+ end
152
+ end
153
+ end
154
+
155
+ def cancel = settle(:cancelled)
156
+
157
+ # The worker leaves.
158
+ def stop = settle(:stopped)
159
+
160
+ # Ends it as +outcome+ (:timed_out, :cancelled, :stopped) now: the
161
+ # bundle test kit's fail_sign_in.
162
+ # @return [Boolean] whether this call ended it
163
+ def end_as(outcome)
164
+ raise ArgumentError, "a sign-in ends :done only through a callback" unless (OUTCOMES - [:done]).include?(outcome)
165
+
166
+ settle(outcome)
167
+ end
168
+
169
+ # Whether +address+ (a pasted one) is this flow's: its redirect_uri,
170
+ # with a query or none.
171
+ def redirect_of?(address)
172
+ return false unless @redirect_uri
173
+
174
+ address == @redirect_uri || address.start_with?("#{@redirect_uri}?")
175
+ end
176
+
177
+ # A callback's query (the browser's, or a pasted address's).
178
+ # @param query [String, nil] the part after "?"
179
+ # @return [Boolean] whether it settled the flow :done
180
+ def offer(query)
181
+ params = parse(query)
182
+ return false if params.nil?
183
+ return false if @state.nil? || params["state"] != @state
184
+
185
+ settle(:done, params)
186
+ end
187
+
188
+ # Its cancel: controller was cancelled: :cancelled; the deadline
189
+ # passed: :timed_out.
190
+ # @return [Boolean] whether this call ended it
191
+ def expire_if_due
192
+ return false unless outcome.nil?
193
+ return settle(:cancelled) if @cancel&.cancelled?
194
+ return settle(:timed_out) if @clock.call >= @deadline
195
+
196
+ false
197
+ end
198
+
199
+ private
200
+
201
+ # @return [Boolean] whether this call settled it
202
+ def settle(outcome, result = nil)
203
+ settled = @mutex.synchronize do
204
+ next false unless @outcome.nil?
205
+
206
+ @outcome = outcome
207
+ @result = result
208
+ @settled.broadcast
209
+ true
210
+ end
211
+ return false unless settled
212
+
213
+ @listener&.close
214
+ @on_settle&.call(self, outcome)
215
+ true
216
+ end
217
+
218
+ def parse(query)
219
+ URI.decode_www_form(query.to_s).each_with_object({}) { |(key, value), params| params[key] ||= value }
220
+ rescue ArgumentError
221
+ nil
222
+ end
223
+
224
+ def state_of(address)
225
+ query = URI.parse(address).query
226
+ query && parse(query)&.fetch("state", nil)
227
+ rescue URI::InvalidURIError
228
+ nil
229
+ end
230
+
231
+ # The loopback end of the round trip: a TCPServer on 127.0.0.1 only
232
+ # (never 0.0.0.0 or ::). It answers only `GET <path>?…`: anything
233
+ # else, or a callback the flow refuses (a wrong state), gets a short
234
+ # 404 and the wait goes on. It reads up to MAX_PENDING connections at
235
+ # once, each with its own deadline (READ_TIMEOUT), so a silent one (a
236
+ # browser's preconnect, a stray local process) never holds the real
237
+ # callback up; a request's line and headers are capped (MAX_REQUEST).
238
+ # A connection that breaks (a reset) is dropped alone. The accepted
239
+ # callback gets a small static page (no script, nothing of the
240
+ # request echoed); then it stops listening. Should its loop fail
241
+ # anyway, it closes the port (a browser gets "refused", never a hang)
242
+ # and tells the flow (on_failed).
243
+ class Listener
244
+ HOST = "127.0.0.1"
245
+ MAX_REQUEST = 8 * 1024
246
+ READ_TIMEOUT = 5.0
247
+ # Connections read at once; a newer one drops the oldest.
248
+ MAX_PENDING = 16
249
+ PAGE = <<~HTML
250
+ <!doctype html><html><head><meta charset="utf-8"><title>Signed in</title></head>
251
+ <body style="font-family:system-ui,sans-serif;margin:3em">Signed in. You can close this tab.</body></html>
252
+ HTML
253
+ NOT_FOUND = "That isn't this sign-in's address.\n"
254
+
255
+ # A connection being read: its socket, what came so far, when it is dropped.
256
+ Pending = Struct.new(:socket, :head, :deadline)
257
+
258
+ attr_reader :port
259
+
260
+ # @param port [Integer, nil] nil: any free one
261
+ # @raise [ArgumentError] the port is taken
262
+ def initialize(port: nil, path: SignIn::DEFAULT_PATH, read_timeout: READ_TIMEOUT, tick: SignIn::TICK)
263
+ @path = path
264
+ @read_timeout = read_timeout
265
+ @tick = tick
266
+ @server = TCPServer.new(HOST, port || 0)
267
+ @port = @server.addr[1]
268
+ @closed = false
269
+ @thread = nil
270
+ rescue Errno::EADDRINUSE, Errno::EACCES
271
+ raise ArgumentError, "ctx.sign_in's port #{port} is taken"
272
+ end
273
+
274
+ def redirect_uri = "http://#{HOST}:#{@port}#{@path}"
275
+
276
+ # @param on_request [#call] (query) → whether it settled the flow
277
+ # @param on_tick [#call] called each TICK (and after each wake-up)
278
+ # @param on_failed [#call, nil] its loop failed: the port is closed
279
+ def start(on_request:, on_tick:, on_failed: nil)
280
+ @thread = Thread.new do
281
+ Thread.current.name = "chi-sign-in"
282
+ serve(on_request, on_tick, on_failed)
283
+ end
284
+ end
285
+
286
+ def closed? = @closed
287
+
288
+ def close
289
+ @closed = true
290
+ @server.close unless @server.closed?
291
+ rescue IOError
292
+ nil
293
+ end
294
+
295
+ private
296
+
297
+ def serve(on_request, on_tick, on_failed)
298
+ pending = []
299
+ until @closed
300
+ ready, = IO.select([@server, *pending.map(&:socket)], nil, nil, wait_seconds(pending))
301
+ on_tick.call
302
+ break if @closed
303
+
304
+ Array(ready).each do |io|
305
+ break if @closed
306
+
307
+ io.equal?(@server) ? admit(pending) : read_more(pending, pending.find { |p| p.socket.equal?(io) }, on_request)
308
+ end
309
+ drop_late(pending)
310
+ end
311
+ rescue StandardError => e # IOError, SystemCallError: closed under it, when @closed
312
+ failed(e, on_failed) unless @closed
313
+ ensure
314
+ pending&.each { |p| drop(pending, p) }
315
+ end
316
+
317
+ def failed(error, on_failed)
318
+ Log.warn(:plugins, "sign_in_listener_failed", error: error.class.name)
319
+ close
320
+ on_failed&.call
321
+ end
322
+
323
+ # Until the next tick or the soonest connection's deadline.
324
+ def wait_seconds(pending)
325
+ soonest = pending.map(&:deadline).min
326
+ return @tick unless soonest
327
+
328
+ (soonest - now).clamp(0.0, @tick)
329
+ end
330
+
331
+ def admit(pending)
332
+ client = @server.accept_nonblock
333
+ drop(pending, pending.first) if pending.size >= MAX_PENDING
334
+ pending << Pending.new(client, +"", now + @read_timeout)
335
+ rescue IO::WaitReadable, Errno::EINTR, Errno::ECONNABORTED
336
+ nil
337
+ end
338
+
339
+ # Its next chunk; a whole head is answered. A connection that broke
340
+ # (reset, closed), ran past MAX_REQUEST or was answered is dropped.
341
+ def read_more(pending, conn, on_request)
342
+ return unless conn
343
+
344
+ chunk = conn.socket.read_nonblock(4096, exception: false)
345
+ return if chunk == :wait_readable
346
+ return drop(pending, conn) if chunk.nil?
347
+
348
+ conn.head << chunk
349
+ return drop(pending, conn) if conn.head.bytesize > MAX_REQUEST
350
+ return unless conn.head.include?("\r\n\r\n") || conn.head.include?("\n\n")
351
+
352
+ answer(conn.socket, conn.head, on_request)
353
+ drop(pending, conn)
354
+ rescue IOError, SystemCallError
355
+ drop(pending, conn)
356
+ end
357
+
358
+ def drop_late(pending)
359
+ at = now
360
+ pending.select { |conn| conn.deadline <= at }.each { |conn| drop(pending, conn) }
361
+ end
362
+
363
+ def drop(pending, conn)
364
+ pending.delete(conn)
365
+ conn.socket.close unless conn.socket.closed?
366
+ rescue IOError, SystemCallError
367
+ nil
368
+ end
369
+
370
+ def answer(client, head, on_request)
371
+ method, target = head.lines.first.to_s.split(" ", 3)
372
+ path, query = target.to_s.split("?", 2)
373
+ if method == "GET" && path == @path && on_request.call(query)
374
+ respond(client, "200 OK", "text/html; charset=utf-8", PAGE)
375
+ close
376
+ else
377
+ respond(client, "404 Not Found", "text/plain; charset=utf-8", NOT_FOUND)
378
+ end
379
+ end
380
+
381
+ def respond(client, status, type, body)
382
+ client.write("HTTP/1.1 #{status}\r\nContent-Type: #{type}\r\nContent-Length: #{body.bytesize}\r\n" \
383
+ "Cache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\n#{body}")
384
+ rescue IOError, SystemCallError
385
+ nil
386
+ end
387
+
388
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
389
+ end
390
+ end
391
+ end
392
+ end