samagotchi 0.119.0 → 0.120.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 (65) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +66 -1
  3. data/bin/chi +6 -1
  4. data/docs/architecture.md +35 -5
  5. data/docs/cli.md +33 -8
  6. data/docs/configuration.md +45 -10
  7. data/docs/internals/participants.md +109 -12
  8. data/docs/internals/remote-sessions.md +6 -1
  9. data/docs/internals/web-push.md +4 -2
  10. data/docs/sessions.md +4 -3
  11. data/docs/testing.md +10 -1
  12. data/lib/samagotchi/answer_command.rb +2 -0
  13. data/lib/samagotchi/bridge.rb +56 -13
  14. data/lib/samagotchi/bridge_client/event_stream.rb +34 -3
  15. data/lib/samagotchi/bridge_client.rb +58 -19
  16. data/lib/samagotchi/bridge_secret.rb +35 -0
  17. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  18. data/lib/samagotchi/config.rb +3 -0
  19. data/lib/samagotchi/participant_messages.rb +5 -0
  20. data/lib/samagotchi/participants.rb +16 -6
  21. data/lib/samagotchi/review_command.rb +3 -1
  22. data/lib/samagotchi/run_options.rb +3 -1
  23. data/lib/samagotchi/session_access/contract.rb +4 -1
  24. data/lib/samagotchi/session_access/local.rb +15 -4
  25. data/lib/samagotchi/session_access/remote.rb +43 -7
  26. data/lib/samagotchi/session_access.rb +11 -1
  27. data/lib/samagotchi/session_manager.rb +1 -1
  28. data/lib/samagotchi/sessions_command.rb +1 -2
  29. data/lib/samagotchi/share_command.rb +29 -8
  30. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -0
  31. data/lib/samagotchi/terminal_ui/local_link.rb +18 -3
  32. data/lib/samagotchi/tools/delegate_relay.rb +4 -0
  33. data/lib/samagotchi/version.rb +1 -1
  34. data/lib/samagotchi/web/app.rb +117 -43
  35. data/lib/samagotchi/web/grants.rb +127 -16
  36. data/lib/samagotchi/web/link_codes.rb +24 -15
  37. data/lib/samagotchi/web/participant_access.rb +69 -13
  38. data/lib/samagotchi/web/participant_exposure.rb +44 -0
  39. data/lib/samagotchi/web/participant_review.rb +66 -8
  40. data/lib/samagotchi/web/participants_admin.rb +12 -6
  41. data/lib/samagotchi/web/proxy_gate.rb +18 -3
  42. data/lib/samagotchi/web/public/annotate_bar.css +18 -0
  43. data/lib/samagotchi/web/public/annotate_bar.js +10 -3
  44. data/lib/samagotchi/web/public/app.js +66 -155
  45. data/lib/samagotchi/web/public/composer.css +73 -0
  46. data/lib/samagotchi/web/public/composer_grip.js +21 -15
  47. data/lib/samagotchi/web/public/composer_mount.js +196 -0
  48. data/lib/samagotchi/web/public/index.html +7 -83
  49. data/lib/samagotchi/web/public/notifications.js +58 -8
  50. data/lib/samagotchi/web/public/participant.html +45 -10
  51. data/lib/samagotchi/web/public/participant.js +92 -18
  52. data/lib/samagotchi/web/public/participant_annotate.js +75 -0
  53. data/lib/samagotchi/web/public/participant_model.js +53 -1
  54. data/lib/samagotchi/web/public/participants_panel.js +34 -10
  55. data/lib/samagotchi/web/public/review_history.js +52 -0
  56. data/lib/samagotchi/web/public/scope.js +12 -8
  57. data/lib/samagotchi/web/public/stage_frame.js +9 -4
  58. data/lib/samagotchi/web/public/stage_view.js +4 -4
  59. data/lib/samagotchi/web/push/notifier.rb +17 -3
  60. data/lib/samagotchi/web/running.rb +7 -4
  61. data/lib/samagotchi/web/server.rb +34 -11
  62. data/lib/samagotchi/web/session_create.rb +7 -7
  63. data/lib/samagotchi/web/start_dir.rb +26 -0
  64. data/lib/samagotchi/worker_sidecar.rb +22 -11
  65. metadata +9 -1
@@ -14,6 +14,7 @@ require_relative "../participant_name"
14
14
  require_relative "../session"
15
15
  require_relative "../redacted_inspect"
16
16
  require_relative "private_files"
17
+ require_relative "participant_exposure"
17
18
 
18
19
  module Samagotchi
19
20
  module Web
@@ -74,16 +75,54 @@ module Samagotchi
74
75
  # session".
75
76
  class Invalid < StandardError; end
76
77
 
78
+ # An identity to bind a grant to that isn't one email address.
79
+ class BadIdentity < Invalid
80
+ def initialize(msg = "a link is bound to one email address (name@domain: one @, no spaces or commas, ASCII " \
81
+ "only)") = super
82
+ end
83
+
84
+ # An identity asked of a chi web that can't check one: no auth proxy
85
+ # naming the signed-in user (ProxyGate), so the link would never open.
86
+ class Unbindable < Invalid
87
+ def initialize(msg = "a link can be bound to an email only on a chi web behind an auth proxy that names the " \
88
+ "signed-in user (web.public_url with web.proxy.identity_header, or chi web --tunnel " \
89
+ "tailscale): bound here it would never open") = super
90
+ end
91
+
92
+ # The store's version: 1, and BOUND_VERSION once a grant is bound to
93
+ # an identity, so a chi that knows only 1 and checks (from this one
94
+ # on) doesn't rewrite it. MAX_VERSION is the newest this chi reads
95
+ # and writes; a newer store it reads but never writes (Newer).
96
+ VERSION = 1
97
+ BOUND_VERSION = 2
98
+ MAX_VERSION = 2
99
+
100
+ # A store chi won't write over (Corrupt, Newer): the owner's invite,
101
+ # cap and revoke are refused with its message.
102
+ class Unwritable < StandardError; end
103
+
77
104
  # The store is there but doesn't read (not JSON, a grant without its
78
105
  # digest or expiry): its grants find nothing (fail closed), and
79
106
  # nothing writes over it, which would lose every other grant.
80
- class Corrupt < StandardError
107
+ class Corrupt < Unwritable
81
108
  def initialize(path, reason)
82
109
  super("#{path} can't be read (#{reason}): chi won't write over it; fix it, or move it aside to end " \
83
110
  "every participant's link")
84
111
  end
85
112
  end
86
113
 
114
+ # The store was written by a newer chi (its version above
115
+ # MAX_VERSION): its grants still work here (read as this chi knows
116
+ # them), but nothing writes over it, which would drop what that chi
117
+ # added to them.
118
+ class Newer < Unwritable
119
+ def initialize(path, version)
120
+ super("#{path} was written by a newer chi (grants store version #{version}; this chi knows up to " \
121
+ "#{MAX_VERSION}): chi won't write over it, which would drop what that chi added; update chi " \
122
+ "(chi update)")
123
+ end
124
+ end
125
+
87
126
  # One participant's access to one session. +id+ (p_<8 hex>) names the
88
127
  # participant too: a turn they send is authored "p:<id>" (P3).
89
128
  # +revoked_by+ why it was revoked: "owner", "archive", "delete",
@@ -91,14 +130,26 @@ module Samagotchi
91
130
  # +cap+ (dollars) and +queue+ (turns waiting) as issued; nil in a
92
131
  # grant from before them, which takes the config's (#spend_cap,
93
132
  # #queue_limit).
133
+ # +exposure+: what the participant learns of the review's usage
134
+ # (ParticipantExposure; "own" for every grant today, and for one from
135
+ # before it). Kept as stored: a level this chi doesn't know reads as
136
+ # the narrowest, and is written back as it was.
137
+ # +extra+: the stored keys this chi doesn't know (a newer chi's,
138
+ # such as a field added to a grant without a version bump), written
139
+ # back as they were, so a rewrite here never drops them.
94
140
  Grant = Data.define(:id, :session_id, :digest, :kind, :name, :role, :created_at, :expires_at, :revoked_at,
95
- :revoked_by, :last_used_at, :cap, :queue, :identity) do
141
+ :revoked_by, :last_used_at, :cap, :queue, :identity, :exposure, :extra) do
96
142
  # identity: the proxy identity (an email, lower case) the grant is
97
143
  # bound to, nil for any (ProxyGate; issued from shared-sessions P6).
98
- def initialize(cap: nil, queue: nil, identity: nil, **) = super
144
+ def initialize(cap: nil, queue: nil, identity: nil, exposure: nil, extra: {}, **)
145
+ super(cap: cap, queue: queue, identity: identity, extra: extra,
146
+ exposure: exposure.nil? ? ParticipantExposure::DEFAULT : exposure, **)
147
+ end
99
148
 
100
149
  def self.from_h(hash)
101
- new(**members.to_h { |key| [key, hash[key.to_s]] })
150
+ known = members - [:extra]
151
+ extra = hash.reject { |key, _| known.include?(key.to_s.to_sym) }
152
+ new(**known.to_h { |key| [key, hash[key.to_s]] }, extra: extra)
102
153
  end
103
154
 
104
155
  # The dollars this participant may cost the owner.
@@ -132,11 +183,24 @@ module Samagotchi
132
183
  def public_h(now)
133
184
  { id: id, session_id: session_id, kind: kind, name: name, role: role, created_at: created_at,
134
185
  expires_at: expires_at, revoked_at: revoked_at, revoked_by: revoked_by, last_used_at: last_used_at,
135
- state: state(now).to_s, cap: spend_cap, queue: queue_limit }
186
+ state: state(now).to_s, cap: spend_cap, queue: queue_limit, identity: identity }
136
187
  end
137
188
 
138
- # A grant bound to no identity is stored as before identity existed.
139
- def to_store = to_h.transform_keys(&:to_s).tap { |hash| hash.delete("identity") if identity.nil? }
189
+ # A grant bound to no identity, with the default exposure, is stored
190
+ # as before either existed; the keys this chi doesn't know come
191
+ # after, as they were.
192
+ #
193
+ # A non-default exposure needs no version bump (identity's
194
+ # BOUND_VERSION): a chi that ignores it shows the participant the
195
+ # narrowest level, so it fails closed, and one that knows Grant#extra
196
+ # keeps it on a rewrite. A bump would only make that chi refuse the
197
+ # owner's invite, cap and revoke (Newer) for no safety gain.
198
+ def to_store
199
+ hash = to_h.except(:extra).transform_keys(&:to_s)
200
+ hash.delete("identity") if identity.nil?
201
+ hash.delete("exposure") if exposure == ParticipantExposure::DEFAULT
202
+ hash.merge(extra.reject { |key, _| hash.key?(key) })
203
+ end
140
204
 
141
205
  def inspect = "#<Grant #{id} #{session_id[0, 8]} #{name.inspect}>"
142
206
  alias_method :to_s, :inspect
@@ -191,6 +255,26 @@ module Samagotchi
191
255
 
192
256
  def self.token?(value) = value.is_a?(String) && value.start_with?(PREFIX)
193
257
 
258
+ # What a proxy identity header carries: an email, or a login such as
259
+ # Tailscale's alex@github (one @, a domain without a dot).
260
+ IDENTITY_RE = /\A[^@,<>"\\]+@[^@,<>"\\]+\z/
261
+ # No space or control character anywhere (a header can't carry one,
262
+ # and a name with one could mislead in a listing).
263
+ IDENTITY_BAD_RE = /\p{Space}|\p{Cc}/
264
+ IDENTITY_MAX = 254
265
+
266
+ # +identity+ as the gate compares it (ProxyGate#proxy_identity: strip,
267
+ # lower case).
268
+ # @raise [BadIdentity] not one email address
269
+ def self.clean_identity(identity)
270
+ # ASCII only, as ProxyGate#proxy_identity: its lower case is the same
271
+ # whatever the string's encoding.
272
+ clean = identity.is_a?(String) && identity.ascii_only? ? identity.strip.downcase : ""
273
+ raise BadIdentity unless clean.length <= IDENTITY_MAX && IDENTITY_RE.match?(clean) && !IDENTITY_BAD_RE.match?(clean)
274
+
275
+ clean
276
+ end
277
+
194
278
  # One line, at most NAME_MAX characters, no brackets (a name can't
195
279
  # forge the "[Review contribution from …]" header; ParticipantName).
196
280
  # @raise [Invalid] nothing left
@@ -226,10 +310,12 @@ module Samagotchi
226
310
  # A new grant for +session_id+, written before the token is handed out.
227
311
  # @param ttl [Integer, nil] seconds (nil: Grants.default_ttl; at most MAX_TTL)
228
312
  # @param cap [Numeric, nil] dollars (nil: Grants.default_cap)
313
+ # @param identity [String, nil] the proxy identity (an email) the grant
314
+ # is bound to (Grants.clean_identity), nil for any
229
315
  # @param on_write [#call, nil] see #update
230
316
  # @return [Issued]
231
317
  # @raise [Invalid]
232
- def issue(session_id:, name:, kind: "human", role: "reviewer", ttl: nil, cap: nil, on_write: nil)
318
+ def issue(session_id:, name:, kind: "human", role: "reviewer", ttl: nil, cap: nil, identity: nil, on_write: nil)
233
319
  Session.check_id!(session_id)
234
320
  ttl ||= Grants.default_ttl
235
321
  cap = Grants.default_cap if cap.nil?
@@ -239,13 +325,15 @@ module Samagotchi
239
325
  raise Invalid, CAP_RANGE unless Grants.cap?(cap)
240
326
 
241
327
  clean = Grants.clean_name(name)
328
+ identity = Grants.clean_identity(identity) unless identity.nil?
242
329
  token = "#{PREFIX}#{SecureRandom.urlsafe_base64(BYTES)}"
243
330
  issued = now
244
331
  update(on_write) do |grants|
245
332
  id = fresh_id(grants)
246
333
  grant = Grant.new(id: id, session_id: session_id, digest: Grants.digest(token), kind: kind, name: clean,
247
334
  role: role, created_at: stamp(issued), expires_at: stamp(issued + ttl), revoked_at: nil,
248
- revoked_by: nil, last_used_at: nil, cap: cap.to_f, queue: Grants.default_queue)
335
+ revoked_by: nil, last_used_at: nil, cap: cap.to_f, queue: Grants.default_queue,
336
+ identity: identity)
249
337
  [grants + [grant], Issued.new(grant: grant, token: token)]
250
338
  end
251
339
  end
@@ -335,7 +423,7 @@ module Samagotchi
335
423
  update do |grants|
336
424
  [grants.map { |grant| grant.id == id ? grant.with(last_used_at: stamp(at)) : grant }, nil]
337
425
  end
338
- rescue Corrupt
426
+ rescue Unwritable
339
427
  nil
340
428
  end
341
429
 
@@ -368,8 +456,13 @@ module Samagotchi
368
456
  grants
369
457
  end
370
458
 
459
+ # In a newer chi's store (Newer) a grant with fields this chi doesn't
460
+ # know is left out: such a field may restrict it (a binding moved to a
461
+ # new key), so it fails closed here. Its link works on that chi again.
371
462
  def reload(stamp)
372
- @grants = stamp ? read : []
463
+ grants, version = stamp ? read : [[], VERSION]
464
+ grants = grants.select { |grant| grant.extra.empty? } if version > MAX_VERSION
465
+ @grants = grants
373
466
  @corrupt = nil
374
467
  rescue Corrupt => e
375
468
  @grants = []
@@ -377,19 +470,23 @@ module Samagotchi
377
470
  Log.warn(:web, "grants_unreadable", echo: "[chi web] #{e.message}", path: @path)
378
471
  end
379
472
 
473
+ # [grants, the store's version] (none yet: [[], VERSION]).
380
474
  # @raise [Corrupt] the file is there but isn't a grants store
381
475
  def read
382
476
  data = begin
383
477
  JSON.parse(File.read(@path))
384
478
  rescue Errno::ENOENT
385
- return []
479
+ return [[], VERSION]
386
480
  rescue JSON::ParserError
387
481
  raise Corrupt.new(@path, "not JSON")
388
482
  end
389
483
  rows = data.is_a?(Hash) ? data["grants"] : nil
390
484
  raise Corrupt.new(@path, "no grants list") unless rows.is_a?(Array)
391
485
 
392
- rows.each_with_index.map { |hash, index| grant_from(hash, index) }
486
+ version = data.fetch("version", VERSION)
487
+ raise Corrupt.new(@path, "a bad version") unless version.is_a?(Integer) && version >= VERSION
488
+
489
+ [rows.each_with_index.map { |hash, index| grant_from(hash, index) }, version]
393
490
  end
394
491
 
395
492
  # A stored grant the gate can compare and date, else Corrupt.
@@ -401,12 +498,21 @@ module Samagotchi
401
498
  elsif !grant.digest.is_a?(String) || grant.digest.empty? then "no digest"
402
499
  elsif !time?(grant.expires_at) then "no expiry"
403
500
  elsif !grant.revoked_at.nil? && !time?(grant.revoked_at) then "a bad revoked_at"
501
+ elsif !identity?(grant.identity) then "a bad identity"
404
502
  end
405
503
  raise Corrupt.new(@path, "grant #{index + 1} has #{problem}") if problem
406
504
 
407
505
  grant
408
506
  end
409
507
 
508
+ # nil (unbound), or an identity as #issue stores it: anything else
509
+ # (false, "", a list) could read as unbound.
510
+ def identity?(value)
511
+ value.nil? || (value.is_a?(String) && Grants.clean_identity(value) == value)
512
+ rescue BadIdentity
513
+ false
514
+ end
515
+
410
516
  def time?(value)
411
517
  value.is_a?(String) && Time.iso8601(value)
412
518
  rescue ArgumentError
@@ -427,11 +533,16 @@ module Samagotchi
427
533
  File.open(File.join(dir, LOCK), File::RDWR | File::CREAT, 0o600) do |lock|
428
534
  lock.flock(File::LOCK_EX)
429
535
  # Never over a store that didn't read (Corrupt): the next write
430
- # would keep only this one's change.
431
- grants, result = yield(read)
536
+ # would keep only this one's change. Nor over a newer chi's
537
+ # (Newer): this chi would drop what it doesn't know.
538
+ stored, version = read
539
+ raise Newer.new(@path, version) if version > MAX_VERSION
540
+
541
+ grants, result = yield(stored)
432
542
  at = now
433
543
  kept = grants.reject { |grant| (ended = grant.ended_at(at)) && at - ended > KEEP_ENDED }
434
- body = JSON.pretty_generate({ "version" => 1, "grants" => kept.map(&:to_store) })
544
+ version = [version, kept.any?(&:identity) ? BOUND_VERSION : VERSION].max
545
+ body = JSON.pretty_generate({ "version" => version, "grants" => kept.map(&:to_store) })
435
546
  AtomicFile.write(@path, "#{body}\n", perm: 0o600)
436
547
  @mutex.synchronize { @stamp = nil }
437
548
  on_write&.call(kept, result)
@@ -56,25 +56,38 @@ module Samagotchi
56
56
  end
57
57
 
58
58
  # The code's [kind, token] (token nil for the owner's), once: the code
59
- # is gone after. nil for an unknown, used or expired code.
59
+ # is gone after. nil for an unknown, used or expired code. With a
60
+ # block, it is asked (kind, token) first, under the lock: false keeps
61
+ # the code for another try and gives nil (a bound grant's code opened
62
+ # by another identity: decision C).
60
63
  def redeem(code)
61
64
  return nil unless LinkCodes.code?(code)
62
65
 
63
66
  wanted = digest(code)
64
- found = nil
67
+ result = nil
65
68
  update do |entries|
66
- entries.reject do |entry|
67
- next false unless same_digest?(entry["digest"].to_s, wanted)
69
+ entry = entries.find { |candidate| same_digest?(candidate["digest"].to_s, wanted) }
70
+ next entries unless entry
68
71
 
69
- found = entry
70
- true
71
- end
72
+ opened = open_entry(code, entry)
73
+ next entries if opened && block_given? && !yield(*opened)
74
+
75
+ result = opened
76
+ entries.reject { |candidate| candidate.equal?(entry) }
72
77
  end
73
- return nil unless found
74
- return nil if Time.iso8601(found["expires_at"]) <= @clock.call
78
+ result
79
+ end
80
+
81
+ private
82
+
83
+ def digest(code) = Digest::SHA256.hexdigest(code)
75
84
 
76
- kind = found["kind"] == "grant" ? :grant : :owner
77
- token = found["sealed"] && unseal(code, found["sealed"])
85
+ # [kind, token] for a live entry whose token unseals, else nil.
86
+ def open_entry(code, entry)
87
+ return nil if Time.iso8601(entry["expires_at"].to_s) <= @clock.call
88
+
89
+ kind = entry["kind"] == "grant" ? :grant : :owner
90
+ token = entry["sealed"] && unseal(code, entry["sealed"])
78
91
  return nil if kind == :grant && token.nil?
79
92
 
80
93
  [kind, token]
@@ -82,10 +95,6 @@ module Samagotchi
82
95
  nil
83
96
  end
84
97
 
85
- private
86
-
87
- def digest(code) = Digest::SHA256.hexdigest(code)
88
-
89
98
  def same_digest?(left, right) = left.bytesize == right.bytesize && OpenSSL.fixed_length_secure_compare(left, right)
90
99
 
91
100
  def key(code) = OpenSSL::KDF.hkdf(code, salt: "chi-link-code", info: "seal", length: 32, hash: "SHA256")
@@ -19,7 +19,8 @@ module Samagotchi
19
19
  module Web
20
20
  # What a participant (a Web::Grants token) may do in chi web, mixed into
21
21
  # App: the gate's lookup of their grant, the refusals that are theirs
22
- # (token_revoked, token_expired with its ended page, another session's
22
+ # (token_revoked, token_expired with its ended page, token_bound for a
23
+ # link bound to another account, another session's
23
24
  # 404, not_permitted by role), the trimmed answers of their own routes
24
25
  # (info, the session, resolve, a wait on their turn), their turns, and
25
26
  # the running check that ends their streams when the grant does. What
@@ -30,6 +31,11 @@ module Samagotchi
30
31
  # A participant's refused routes are audited at most this often per
31
32
  # route (a page retrying would fill the log).
32
33
  REFUSED_AUDIT_INTERVAL = 60.0
34
+ # At most this many refusals a minute are remembered per reason, so
35
+ # audited: rotating paths or headers can't grow the map or the audit
36
+ # file without bound (as App::REFUSED_LOG_KEYS for the log), nor one
37
+ # reason's flood silence another's.
38
+ REFUSED_AUDIT_KEYS = 256
33
39
 
34
40
  ENDED = {
35
41
  revoked: ["token_revoked", ParticipantMessages::TOKEN_REVOKED],
@@ -65,8 +71,8 @@ module Samagotchi
65
71
  def participant_principal(req, tokens, identity: nil, proxied: false)
66
72
  tokens.each do |token|
67
73
  grant = @grants.lookup(token) or next
68
- if grant.identity && !(proxied && identity == grant.identity)
69
- req.env[ProxyGate::REFUSED_ENV] = "grant #{grant.id} is bound to another identity than #{identity || "(none)"}"
74
+ unless bound_ok?(grant, identity, proxied)
75
+ refuse_bound(req, grant, identity)
70
76
  next
71
77
  end
72
78
  grant = settle_grant(grant)
@@ -82,6 +88,36 @@ module Samagotchi
82
88
 
83
89
  GRANT_TOKEN_ENV = "samagotchi.grant_token"
84
90
  ENDED_GRANT_ENV = "samagotchi.ended_grant"
91
+ BOUND_GRANT_ENV = "samagotchi.bound_grant"
92
+
93
+ # Whether +grant+ may be used by this request: an unbound one anywhere,
94
+ # a bound one only proxied and only for its identity (the one check,
95
+ # for the gate and for a link code's trade).
96
+ def bound_ok?(grant, identity, proxied)
97
+ grant.identity.nil? || (proxied && !identity.nil? && identity == grant.identity)
98
+ end
99
+
100
+ # A bound grant presented by another identity, or not through the
101
+ # proxy: #grant_bound_response answers it (token_bound).
102
+ def refuse_bound(req, grant, identity)
103
+ req.env[ProxyGate::REFUSED_ENV] = "grant #{grant.id} is bound to another identity than #{identity || "(none)"}"
104
+ req.env[BOUND_GRANT_ENV] ||= [grant, identity]
105
+ end
106
+
107
+ # 401 token_bound for a bound grant's token (or link code) presented
108
+ # without its identity (the page's HTML says the same words), nil when
109
+ # none was: logged as a refusal and audited in the grant's session.
110
+ def grant_bound_response(req)
111
+ grant, identity = req.env[BOUND_GRANT_ENV]
112
+ return nil unless grant
113
+
114
+ log_refused(refused_peer(req), req.path_info, "grant #{grant.id} is bound to another identity than #{identity || "(none)"}")
115
+ audit_refused(req, grant, reason: "token_bound", per_route: false, identity: (identity || "(none)")[0, 200])
116
+ detail = ParticipantMessages::TOKEN_BOUND
117
+ return error_response(401, "token_bound", detail) if req.path_info.start_with?("/api/")
118
+
119
+ html_response(401, BOUND_PAGE.sub(ENDED_SENTENCE, "#{detail[0].upcase}#{detail[1..]}."))
120
+ end
85
121
 
86
122
  def settle_grant(grant)
87
123
  return grant unless grant.active?(@grants.now)
@@ -93,6 +129,9 @@ module Samagotchi
93
129
 
94
130
  Participants.revoke(@grants, session_id: grant.session_id, id: grant.id, by: by, state_dir: default_state_dir)
95
131
  @grants.find(grant.id) || grant
132
+ rescue Grants::Unwritable
133
+ # A store this chi can't write (a newer chi's): refused all the same.
134
+ grant.with(revoked_at: @grants.now.utc.iso8601, revoked_by: by)
96
135
  end
97
136
 
98
137
  # 401 token_revoked / token_expired for an ended grant's token (the
@@ -115,16 +154,24 @@ module Samagotchi
115
154
 
116
155
  # A participant's request, past the gate: its use is recorded (the
117
156
  # grant's last_used_at, at most once a minute) and a peer not seen
118
- # since chi web started goes into the audit trail.
157
+ # since chi web started goes into the audit trail. Behind a proxy
158
+ # every peer is 127.0.0.1: there the peer is the client's identity
159
+ # (else the proxy's X-Forwarded-For hop, #refused_peer), and the line
160
+ # names the identity.
119
161
  def participant_seen(req, principal)
120
162
  grant = principal.grant
121
163
  @grants.touch(grant.id)
122
- peer = req.get_header("REMOTE_ADDR").to_s
164
+ peer = refused_peer(req)
123
165
  fresh = @participant_mutex.synchronize { @participant_peers[grant.id].add?(peer) }
124
166
  return unless fresh
125
167
 
126
- Participants.log(grant.session_id, :peer, state_dir: default_state_dir, participant: grant.id, ip: peer,
127
- user_agent: req.get_header("HTTP_USER_AGENT").to_s[0, 200])
168
+ fields = { ip: req.get_header("REMOTE_ADDR").to_s, user_agent: req.get_header("HTTP_USER_AGENT").to_s[0, 200] }
169
+ if proxied?(req)
170
+ state, identity = proxy_identity(req)
171
+ fields[:identity] = identity if state == :ok
172
+ fields[:peer] = peer
173
+ end
174
+ Participants.log(grant.session_id, :peer, state_dir: default_state_dir, participant: grant.id, **fields)
128
175
  end
129
176
 
130
177
  # A participant asking for a session that isn't their grant's: 404 as
@@ -146,19 +193,27 @@ module Samagotchi
146
193
  error_response(403, "not_permitted", NOT_PERMITTED)
147
194
  end
148
195
 
149
- def audit_refused(req, grant)
150
- key = [grant.id, req.request_method, req.path_info]
196
+ # +reason+ and +fields+ go into the line (a bound refusal names the
197
+ # identity that presented it). Once a minute per route for
198
+ # not_permitted; once a minute per grant and identity for a bound
199
+ # refusal, whatever the path (+per_route+ false); at most
200
+ # REFUSED_AUDIT_KEYS keys a minute.
201
+ def audit_refused(req, grant, reason: "not_permitted", per_route: true, **fields)
202
+ key = per_route ? [grant.id, req.request_method, req.path_info, reason, fields] : [grant.id, reason, fields]
151
203
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
152
204
  due = @participant_mutex.synchronize do
153
- @participant_refused.delete_if { |_, at| now - at >= REFUSED_AUDIT_INTERVAL } if @participant_refused.size > 256
154
- last = @participant_refused[key]
155
- (last.nil? || now - last >= REFUSED_AUDIT_INTERVAL).tap { |fresh| @participant_refused[key] = now if fresh }
205
+ seen = (@participant_refused[reason] ||= {})
206
+ seen.delete_if { |_, at| now - at >= REFUSED_AUDIT_INTERVAL } if seen.size > 64
207
+ next false if seen.size >= REFUSED_AUDIT_KEYS && !seen.key?(key)
208
+
209
+ last = seen[key]
210
+ (last.nil? || now - last >= REFUSED_AUDIT_INTERVAL).tap { |fresh| seen[key] = now if fresh }
156
211
  end
157
212
  return unless due
158
213
 
159
214
  Participants.log(grant.session_id, :refused, state_dir: default_state_dir, participant: grant.id,
160
215
  method: req.request_method, path: req.path_info[0, 200],
161
- reason: "not_permitted")
216
+ reason: reason, **fields)
162
217
  end
163
218
 
164
219
  # GET /api/info for a participant: what SessionAccess::Remote's
@@ -405,6 +460,7 @@ module Samagotchi
405
460
  <p>{sentence}</p>
406
461
  </body></html>
407
462
  HTML
463
+ BOUND_PAGE = ENDED_PAGE.sub("<title>chi: review link ended</title>", "<title>chi: review link for another account</title>")
408
464
  end
409
465
  end
410
466
  end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ module Web
5
+ # What a participant may learn of their review's usage, by their grant's
6
+ # exposure level (Grants::Grant#exposure; the review-composer plan's D3):
7
+ # the policy that maps a level to the usage fields the review route
8
+ # gives them (ParticipantReview#review_usage). One level today:
9
+ #
10
+ # - +own+ (every grant's): their own spend and cap, their own queued
11
+ # turns and queue limit, their link's expiry, the session's model.
12
+ # Never another participant's or the owner's usage, nor the session's.
13
+ #
14
+ # A later level (a tier that also shows the session's spend, say) adds
15
+ # its row to LEVELS and its fields' sources in ParticipantReview: one
16
+ # place each. A level this chi doesn't know (written by a newer chi, or
17
+ # a hand-edited store) reads as DEFAULT, the narrowest: an unknown level
18
+ # never shows more. See docs/internals/participants.md (Exposure).
19
+ module ParticipantExposure
20
+ OWN = "own"
21
+ DEFAULT = OWN
22
+ # level => the usage fields it shows, in the order the page reads them.
23
+ LEVELS = {
24
+ OWN => %i[spent cap queued queue_limit expires_at model].freeze
25
+ }.freeze
26
+
27
+ # +value+ as a level this chi knows, else DEFAULT.
28
+ def self.level(value) = LEVELS.key?(value) ? value : DEFAULT
29
+
30
+ # @return [Array<Symbol>] the fields +value+'s level shows
31
+ def self.fields(value) = LEVELS.fetch(level(value))
32
+
33
+ # The usage +value+'s level shows, each field read from +sources+
34
+ # (field => a callable): only the fields shown are computed, and a
35
+ # field a level names with no source raises (KeyError), never shows
36
+ # nothing silently.
37
+ # @param sources [Hash{Symbol => #call}]
38
+ # @return [Hash{Symbol => Object}]
39
+ def self.usage(value, sources)
40
+ fields(value).to_h { |field| [field, sources.fetch(field).call] }
41
+ end
42
+ end
43
+ end
44
+ end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "participant_view"
4
4
  require_relative "participant_stream_filter"
5
+ require_relative "participant_exposure"
5
6
  require_relative "../session_metrics"
6
7
  require_relative "../review_start"
7
8
  require_relative "../guardrails/review_paths"
@@ -58,15 +59,16 @@ module Samagotchi
58
59
  automatic = automatic_turn_ids(id, session, shown, current, state)
59
60
  waiting = !!(current&.dig("waiting_for_owner") || turn_snapshot&.dig("continue_offer") ||
60
61
  (turn_snapshot && !turn_snapshot["current_turn"] && turn_snapshot["pending_question"]))
62
+ queued = snapshot_list(turn_snapshot, "queued")
61
63
  json_response(200, {
62
- viewer: review_viewer(req, id),
64
+ viewer: review_viewer(req, id, session: session, state: state, queued: queued, viewer: viewer),
63
65
  session: { id: session.id, title: participant_title(session), status: displayed_status(session, state) },
64
66
  subjects: review_subjects(session, viewer),
65
67
  participants: participant_names(id).map { |entry| entry.slice(:id, :name, :kind) },
66
68
  messages: with_reply_html(ParticipantView.messages(shown, viewer, automatic: automatic)),
67
69
  current_turn: current,
68
70
  waiting_for_owner: waiting,
69
- queued: review_queue(snapshot_list(turn_snapshot, "queued"), viewer),
71
+ queued: review_queue(queued, viewer),
70
72
  last_event_id: turn_snapshot && turn_snapshot["event_id"]
71
73
  })
72
74
  end
@@ -140,15 +142,69 @@ module Samagotchi
140
142
  def delegate_child?(session) = !session.parent_id.to_s.empty?
141
143
 
142
144
  # Who is reading: a participant (their id, name, whether they may
143
- # comment: not once their cap is reached), or the owner looking
144
- # through the participant view (no composer).
145
- def review_viewer(req, id)
145
+ # comment: not once their cap is reached, and their +usage+ as their
146
+ # grant's exposure shows it), or the owner looking through the
147
+ # participant view (no composer, no usage: the owner has /stats).
148
+ # +state+ the live worker's session state (nil without one), +queued+
149
+ # its queue.
150
+ def review_viewer(req, id, session:, state:, queued:, viewer:)
146
151
  return { kind: "owner", can_comment: false } if principal(req).owner?
147
152
 
148
153
  grant = principal(req).grant
149
154
  capped = !participant_cap_refusal(grant).nil?
150
155
  { kind: "participant", id: grant.id, name: grant.name, participant_kind: grant.kind, can_comment: !capped,
151
- cap_reached: capped, session_id: id }
156
+ cap_reached: capped, session_id: id,
157
+ usage: review_usage(grant, session: session, state: state, queued: queued, viewer: viewer) }
158
+ end
159
+
160
+ # A participant's usage, the fields their grant's exposure level
161
+ # shows (ParticipantExposure), each computed only when shown. Every
162
+ # source reads the grant's own author: never another participant's or
163
+ # the owner's.
164
+ def review_usage(grant, session:, state:, queued:, viewer:)
165
+ ParticipantExposure.usage(grant.exposure, {
166
+ spent: -> { participant_spent(grant, state) },
167
+ cap: -> { grant.spend_cap },
168
+ queued: -> { queued.count { |entry| entry.is_a?(Hash) && viewer.own?(entry["author"]) } },
169
+ queue_limit: -> { grant.queue_limit },
170
+ expires_at: -> { grant.expires_at },
171
+ model: -> { participant_model(session, state, viewer) }
172
+ })
173
+ end
174
+
175
+ # What the participant has cost so far, in dollars: the saved
176
+ # analytics' count (#participant_cap_refusal's), or the live worker's
177
+ # when it is more (SessionMetrics#spend: its saved turns, the running
178
+ # turn's finished generations and the side requests; a running turn
179
+ # is saved only at its end). The worker's count already holds the
180
+ # saved one, so the two are never added.
181
+ def participant_spent(grant, state)
182
+ dir = Session.session_dir(grant.session_id, state_dir: default_state_dir)
183
+ saved = SessionMetrics.saved_spend(dir, grant.author)
184
+ live = live_spend(state, grant.author)
185
+ [saved, live].max.round(4)
186
+ end
187
+
188
+ # +author+'s cost in the live worker's metrics (spend_by_author), 0.0
189
+ # without one.
190
+ def live_spend(state, author)
191
+ cost = state.is_a?(Hash) ? state.dig("metrics", "spend_by_author", author, "cost") : nil
192
+ cost.is_a?(Numeric) && cost.to_f.finite? ? cost.to_f : 0.0
193
+ rescue TypeError
194
+ 0.0
195
+ end
196
+
197
+ # The model the session runs on, as its host is sent it (the alias
198
+ # applied, no host name): the live worker's, else the saved one's;
199
+ # nil when it doesn't resolve.
200
+ def participant_model(session, state, viewer)
201
+ ref = (state.is_a?(Hash) && state["model_name"]) || session.model_name
202
+ return nil if ref.to_s.empty?
203
+
204
+ name = host_registry.bare_name(ref.to_s)
205
+ name.to_s.empty? ? nil : ParticipantView::Redact.text(name.to_s, viewer)
206
+ rescue StandardError
207
+ nil
152
208
  end
153
209
 
154
210
  # The queue as a participant sees it: their own queued turns (the
@@ -185,8 +241,10 @@ module Samagotchi
185
241
  grant = principal(req).grant
186
242
  attrs.merge!("viewer" => "participant", "session" => grant.session_id, "name" => grant.name)
187
243
  end
188
- data = attrs.map { |key, value| %(data-#{key}="#{Rack::Utils.escape_html(value)}") }.join(" ")
189
- html_response(200, File.read(path).sub("<body>", "<body #{data}>"))
244
+ # The owner's participant view has no composer; a participant's
245
+ # selection quotes with the same presets as the owner's page.
246
+ attrs.merge!(annotate_presets_data) unless principal(req).owner?
247
+ html_response(200, File.read(path).sub("<body>", "<body #{body_data(attrs)}>"))
190
248
  end
191
249
 
192
250
  # A filtered stream's frame filter (App#stream_filter), for the