samagotchi 0.107.0 → 0.109.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 (74) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +69 -1
  3. data/docs/architecture.md +10 -4
  4. data/docs/configuration.md +81 -0
  5. data/docs/internals/engine.md +17 -6
  6. data/docs/internals/participants.md +28 -8
  7. data/docs/internals/remote-sessions.md +6 -2
  8. data/docs/internals/working-set.md +2 -1
  9. data/docs/memory.md +20 -0
  10. data/docs/plugins.md +9 -2
  11. data/docs/releasing.md +11 -6
  12. data/docs/sessions.md +3 -3
  13. data/docs/sub-agent.md +1 -1
  14. data/docs/testing.md +5 -1
  15. data/lib/samagotchi/bridge/turn_accumulator.rb +3 -2
  16. data/lib/samagotchi/bridge.rb +28 -2
  17. data/lib/samagotchi/bundles/cost-cap/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/cost-cap/plugin.rb +51 -9
  19. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  21. data/lib/samagotchi/bundles/work-cap/manifest.yml +2 -2
  22. data/lib/samagotchi/bundles/work-cap/plugin.rb +50 -14
  23. data/lib/samagotchi/child_reports.rb +2 -1
  24. data/lib/samagotchi/cli/parent_wait.rb +1 -1
  25. data/lib/samagotchi/config.rb +4 -0
  26. data/lib/samagotchi/context_sources.rb +1 -6
  27. data/lib/samagotchi/continue_offer.rb +8 -6
  28. data/lib/samagotchi/engine.rb +36 -25
  29. data/lib/samagotchi/guardrail_wiring.rb +9 -6
  30. data/lib/samagotchi/idle_scheduler.rb +17 -2
  31. data/lib/samagotchi/last_turn.rb +7 -0
  32. data/lib/samagotchi/log_subscriber.rb +2 -1
  33. data/lib/samagotchi/memory_orphans.rb +74 -0
  34. data/lib/samagotchi/memory_paths.rb +4 -4
  35. data/lib/samagotchi/parent_report.rb +11 -3
  36. data/lib/samagotchi/proxy_trace.rb +45 -0
  37. data/lib/samagotchi/reply_wait.rb +7 -2
  38. data/lib/samagotchi/send_command/busy.rb +5 -2
  39. data/lib/samagotchi/send_command/wait_target.rb +16 -11
  40. data/lib/samagotchi/session_access/local.rb +46 -10
  41. data/lib/samagotchi/session_inbox.rb +12 -8
  42. data/lib/samagotchi/session_metrics.rb +7 -6
  43. data/lib/samagotchi/session_participants.rb +3 -1
  44. data/lib/samagotchi/steer.rb +11 -1
  45. data/lib/samagotchi/terminal_ui/attached_loop.rb +30 -26
  46. data/lib/samagotchi/terminal_ui/formatting.rb +2 -2
  47. data/lib/samagotchi/terminal_ui/one_shot_sink.rb +5 -1
  48. data/lib/samagotchi/tools/memory.rb +16 -9
  49. data/lib/samagotchi/turn_origin.rb +68 -0
  50. data/lib/samagotchi/version.rb +1 -1
  51. data/lib/samagotchi/web/app.rb +233 -26
  52. data/lib/samagotchi/web/grants.rb +8 -4
  53. data/lib/samagotchi/web/info_probe.rb +5 -1
  54. data/lib/samagotchi/web/link_codes.rb +146 -0
  55. data/lib/samagotchi/web/participant_access.rb +15 -118
  56. data/lib/samagotchi/web/participant_review.rb +1 -1
  57. data/lib/samagotchi/web/participant_view.rb +7 -13
  58. data/lib/samagotchi/web/participants_admin.rb +136 -0
  59. data/lib/samagotchi/web/proxy_gate.rb +174 -0
  60. data/lib/samagotchi/web/public/app.js +24 -0
  61. data/lib/samagotchi/web/public/auth_lost.js +76 -0
  62. data/lib/samagotchi/web/public/data.js +29 -5
  63. data/lib/samagotchi/web/public/participant.js +19 -5
  64. data/lib/samagotchi/web/public/participant_model.js +5 -0
  65. data/lib/samagotchi/web/public/participant_names.js +2 -2
  66. data/lib/samagotchi/web/public/participants_panel.js +2 -2
  67. data/lib/samagotchi/web/public/token_fragment.js +57 -0
  68. data/lib/samagotchi/web/public_url.rb +87 -0
  69. data/lib/samagotchi/web/server.rb +70 -10
  70. data/lib/samagotchi/worker.rb +30 -25
  71. data/lib/samagotchi/worker_inbound.rb +12 -9
  72. data/lib/samagotchi/worker_sidecar.rb +4 -3
  73. data/lib/samagotchi/working_set.rb +3 -2
  74. metadata +10 -1
@@ -4,15 +4,12 @@ require "json"
4
4
  require_relative "grants"
5
5
  require_relative "principal"
6
6
  require_relative "participant_view"
7
- require_relative "qr"
8
7
  require_relative "../archive_store"
9
8
  require_relative "../client_id"
10
9
  require_relative "../delivery"
11
10
  require_relative "../session_inbox"
12
11
  require_relative "../session_metrics"
13
12
  require_relative "../parent_report"
14
- require_relative "../review_start"
15
- require_relative "../review_apply"
16
13
  require_relative "../participant_messages"
17
14
  require_relative "../participants"
18
15
  require_relative "../session"
@@ -22,10 +19,12 @@ module Samagotchi
22
19
  module Web
23
20
  # What a participant (a Web::Grants token) may do in chi web, mixed into
24
21
  # App: the gate's lookup of their grant, the refusals that are theirs
25
- # (token_revoked, token_expired, another session's 404, not_permitted
26
- # by role), the trimmed answers of the :participant routes, their turns,
27
- # and the running check that ends their streams when the grant does
28
- # (what they read is ParticipantReview's). See
22
+ # (token_revoked, token_expired with its ended page, another session's
23
+ # 404, not_permitted by role), the trimmed answers of their own routes
24
+ # (info, the session, resolve, a wait on their turn), their turns, and
25
+ # the running check that ends their streams when the grant does. What
26
+ # they read is ParticipantReview's; the owner's routes for them (invite,
27
+ # list, revoke, cap, Apply) are ParticipantsAdmin's. See
29
28
  # docs/internals/participants.md.
30
29
  module ParticipantAccess
31
30
  # A participant's refused routes are audited at most this often per
@@ -58,11 +57,18 @@ module Samagotchi
58
57
  # request's env for #token_gate's answer (#grant_ended_response). A
59
58
  # grant whose session was archived or is gone is revoked here (archive
60
59
  # and delete revoke too; this catches retention's prune and a delete
61
- # from another process).
60
+ # from another process). A grant bound to an identity (Grant#identity)
61
+ # is honoured only on a proxied request with that identity
62
+ # (ProxyGate): never on the LAN or this machine.
63
+ # @param identity [String, nil] the proxied request's identity
62
64
  # @return [Principal, nil]
63
- def participant_principal(req, tokens)
65
+ def participant_principal(req, tokens, identity: nil, proxied: false)
64
66
  tokens.each do |token|
65
67
  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)"}"
70
+ next
71
+ end
66
72
  grant = settle_grant(grant)
67
73
  state = grant.state(@grants.now)
68
74
  if state == :active
@@ -376,115 +382,6 @@ module Samagotchi
376
382
  -> { @server_running.call && @grants.active?(id) }
377
383
  end
378
384
 
379
- # ── The owner's routes ─────────────────────────────────────────────
380
-
381
- # GET /api/sessions/:id/participants, GET /api/participants: the
382
- # grants (one session's, or every one), in every state, never a token
383
- # or digest. One session's also carries +warning+: the share warning
384
- # for a session that isn't a review session (ReviewStart.share_warning,
385
- # null for one), which the panel shows before its Invite.
386
- def handle_participants_list(_req, id = nil)
387
- now = @grants.now
388
- grants = @grants.list(session_id: id).map { |grant| grant.public_h(now) }
389
- return json_response(200, { participants: grants }) unless id
390
-
391
- warning = ReviewStart.share_warning(Session.load(id, state_dir: default_state_dir))
392
- json_response(200, { participants: with_spend(id, grants), warning: warning })
393
- end
394
-
395
- # One session's grants with what each spent and how many turns they
396
- # ran (its saved analytics: SessionMetrics.saved_by_author), for the
397
- # owner's participants panel.
398
- def with_spend(id, grants)
399
- rows = SessionMetrics.saved_by_author(Session.session_dir(id, state_dir: default_state_dir))
400
- grants.map do |grant|
401
- row = rows["p:#{grant[:id]}"] || { turns: 0, cost: 0.0 }
402
- grant.merge(spend: row[:cost].round(4), turns: row[:turns])
403
- end
404
- end
405
-
406
- # POST /api/sessions/:id/participants {name, kind?, ttl? (seconds),
407
- # cap? (dollars)}: a new grant. The answer carries the token and the
408
- # link once (chi keeps only its digest), and +warning+ for a session
409
- # that isn't a review session (ReviewStart.share_warning; null for one).
410
- def handle_participants_invite(req, id)
411
- body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
412
- ttl = body["ttl"]
413
- return error_response(400, "invalid_participant", "ttl is a number of seconds") unless ttl.nil? || ttl.is_a?(Integer)
414
-
415
- cap = body["cap"]
416
- return error_response(400, "invalid_participant", Grants::CAP_RANGE) unless cap.nil? || Grants.cap?(cap)
417
-
418
- issued = Participants.invite(@grants, session_id: id, name: body["name"], kind: (body["kind"] || "human").to_s,
419
- ttl: ttl, cap: cap, state_dir: default_state_dir)
420
- link = participant_link(req, id, issued.token)
421
- warning = ReviewStart.share_warning(Session.load(id, state_dir: default_state_dir))
422
- json_response(201, { participant: issued.grant.public_h(@grants.now), token: issued.token,
423
- link: link, lan: !@lan.nil?, qr_svg: QR.svg(link), warning: warning })
424
- rescue Grants::Invalid => e
425
- error_response(400, "invalid_participant", e.message)
426
- end
427
-
428
- # GET /api/sessions/:id/apply[?turn=T] (owner): the owner's turn that
429
- # applies review turn T's proposal (ReviewApply: the reply quoted
430
- # under one line of the owner's), for the composer: never sent from
431
- # here. Without turn, the latest review turn with a reply. Read from
432
- # the live worker's messages, else the saved ones.
433
- # @return 200 {text, turn_id, author, author_name}; 404 not_found (no
434
- # such turn, or no review turn); 400 not_review_turn; 409 no_reply
435
- def handle_apply(req, id)
436
- session = @session_class.load(id, state_dir: default_state_dir)
437
- live = bridge_get_json(id, "snapshot")
438
- messages = live_or_saved(live && live["snapshot"], "messages") { session.messages }
439
- proposal = ReviewApply.find(messages, req.params["turn"])
440
- json_response(200, { text: ReviewApply.compose(proposal), turn_id: proposal.turn_id, author: proposal.author,
441
- author_name: proposal.author_name })
442
- rescue ReviewApply::Refused => e
443
- status = { not_found: 404, not_review_turn: 400, no_reply: 409 }.fetch(e.code)
444
- error_response(status, e.code.to_s, e.message)
445
- end
446
-
447
- # DELETE /api/sessions/:id/participants[?id=p_…], DELETE
448
- # /api/participants: revokes one participant, a session's or every
449
- # one's; their open streams end within a poll.
450
- def handle_participants_revoke(req, id = nil)
451
- grant_id = req.params["id"]
452
- if grant_id && !Grants::ID_RE.match?(grant_id.to_s)
453
- return error_response(400, "invalid_participant", "not a participant id: #{grant_id.to_s[0, 40]}")
454
- end
455
-
456
- revoked = Participants.revoke(@grants, session_id: id, id: grant_id, by: "owner", state_dir: default_state_dir)
457
- now = @grants.now
458
- json_response(200, { revoked: revoked.map { |grant| grant.public_h(now) } })
459
- end
460
-
461
- # POST /api/sessions/:id/participants/:participant/cap {cap}: the
462
- # active participant's new spending cap (dollars), from their next
463
- # turn on. 200 {participant}; 400 invalid_participant.
464
- def handle_participants_cap(req, id, grant_id)
465
- body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
466
- unless Grants::ID_RE.match?(grant_id.to_s)
467
- return error_response(400, "invalid_participant", "not a participant id: #{grant_id.to_s[0, 40]}")
468
- end
469
-
470
- grant = Participants.set_cap(@grants, session_id: id, id: grant_id, cap: body["cap"], state_dir: default_state_dir)
471
- return error_response(400, "invalid_participant", Participants.no_participant(grant_id, id)) unless grant
472
-
473
- json_response(200, { participant: grant.public_h(@grants.now) })
474
- rescue Grants::Invalid => e
475
- error_response(400, "invalid_participant", e.message)
476
- end
477
-
478
- # The link a participant opens: this chi web's LAN address when it has
479
- # one (the owner may be asking on loopback), else the Host asked; the
480
- # token traded for the cookie, the session in the fragment.
481
- def participant_link(req, id, token)
482
- host = req.get_header("HTTP_HOST").to_s
483
- port = host[/:(\d+)\z/, 1] || req.port.to_s
484
- name = @lan ? @lan[:ip] : host.sub(/:\d*\z/, "")
485
- "http://#{name}:#{port}/?token=#{token}#s=#{id}"
486
- end
487
-
488
385
  def html_response(status, body)
489
386
  [status, { "Content-Type" => "text/html; charset=utf-8", "Content-Length" => body.bytesize.to_s,
490
387
  "Cache-Control" => "no-store" }, [body]]
@@ -39,7 +39,7 @@ module Samagotchi
39
39
  # paths; the owner's token is never shown.
40
40
  def participant_viewer(req, session)
41
41
  author = principal(req).owner? ? nil : principal(req).grant.author
42
- ParticipantView::Viewer.new(author: author, cwd: session.working_directory, secrets: [@lan && current_token].compact)
42
+ ParticipantView::Viewer.new(author: author, cwd: session.working_directory, secrets: [(@lan || @public_url) && current_token].compact)
43
43
  end
44
44
 
45
45
  # GET /api/sessions/:id/review: the participant page's data, always
@@ -1,8 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../client_id"
4
3
  require_relative "../output_formatter"
5
4
  require_relative "../steer"
5
+ require_relative "../turn_origin"
6
6
 
7
7
  module Samagotchi
8
8
  module Web
@@ -102,17 +102,18 @@ module Samagotchi
102
102
 
103
103
  # A turn's start: who wrote it, and its prompt when a person sent it
104
104
  # (an automatic turn's prompt, a reminder's or a task's, is not
105
- # shown). +mine+ when the viewer queued it.
105
+ # shown: a person is the owner's web or TUI, chi send, a participant,
106
+ # or no origin, an in-process turn: the owner's; TurnOrigin#human?).
107
+ # +mine+ when the viewer queued it.
106
108
  def turn_started(event, viewer)
107
- origin = field(event, :origin)
108
- origin = {} unless origin.is_a?(Hash)
109
- author = field(event, :author) || field(origin, :author)
109
+ origin = TurnOrigin.of(field(event, :origin))
110
+ author = field(event, :author) || origin.author
110
111
  out = { "type" => "turn_started", **id_fields(event) }
111
112
  out.merge!(author_fields(author, field(event, :author_name), viewer))
112
113
  prompt = field(event, :prompt)
113
114
  if field(event, :continue)
114
115
  out["continue"] = true
115
- elsif person_turn?(origin)
116
+ elsif origin.human?
116
117
  out["prompt"] = prompt.to_s unless prompt.nil?
117
118
  else
118
119
  out["automatic"] = true
@@ -286,13 +287,6 @@ module Samagotchi
286
287
  out
287
288
  end
288
289
 
289
- # Sent by a person (the owner's web or TUI, chi send, a participant),
290
- # or with no origin (an in-process turn: the owner's).
291
- def person_turn?(origin)
292
- client_id = field(origin, :client_id)
293
- client_id.nil? || ClientId.human?(client_id)
294
- end
295
-
296
290
  def id_fields(event)
297
291
  out = seq(event)
298
292
  turn_id = field(event, :turn_id)
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "grants"
4
+ require_relative "qr"
5
+ require_relative "../review_start"
6
+ require_relative "../review_apply"
7
+ require_relative "../session_metrics"
8
+ require_relative "../participants"
9
+ require_relative "../session"
10
+
11
+ module Samagotchi
12
+ module Web
13
+ # The owner's routes for a session's participants, mixed into App:
14
+ # invite, list, revoke, a participant's cap, and the review Apply (the
15
+ # owner's turn quoting a review turn's proposal). What a participant
16
+ # may do themselves is ParticipantAccess's. See
17
+ # docs/internals/participants.md.
18
+ module ParticipantsAdmin
19
+ private
20
+
21
+ # GET /api/sessions/:id/participants, GET /api/participants: the
22
+ # grants (one session's, or every one), in every state, never a token
23
+ # or digest. One session's also carries +warning+: the share warning
24
+ # for a session that isn't a review session (ReviewStart.share_warning,
25
+ # null for one), which the panel shows before its Invite.
26
+ def handle_participants_list(_req, id = nil)
27
+ now = @grants.now
28
+ grants = @grants.list(session_id: id).map { |grant| grant.public_h(now) }
29
+ return json_response(200, { participants: grants }) unless id
30
+
31
+ warning = ReviewStart.share_warning(Session.load(id, state_dir: default_state_dir))
32
+ json_response(200, { participants: with_spend(id, grants), warning: warning })
33
+ end
34
+
35
+ # One session's grants with what each spent and how many turns they
36
+ # ran (its saved analytics: SessionMetrics.saved_by_author), for the
37
+ # owner's participants panel.
38
+ def with_spend(id, grants)
39
+ rows = SessionMetrics.saved_by_author(Session.session_dir(id, state_dir: default_state_dir))
40
+ grants.map do |grant|
41
+ row = rows[Steer.author_for(grant[:id])] || { turns: 0, cost: 0.0 }
42
+ grant.merge(spend: row[:cost].round(4), turns: row[:turns])
43
+ end
44
+ end
45
+
46
+ # POST /api/sessions/:id/participants {name, kind?, ttl? (seconds),
47
+ # cap? (dollars)}: a new grant. The answer carries the token and the
48
+ # link once (chi keeps only its digest), and +warning+ for a session
49
+ # that isn't a review session (ReviewStart.share_warning; null for one).
50
+ def handle_participants_invite(req, id)
51
+ body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
52
+ ttl = body["ttl"]
53
+ return error_response(400, "invalid_participant", "ttl is a number of seconds") unless ttl.nil? || ttl.is_a?(Integer)
54
+
55
+ cap = body["cap"]
56
+ return error_response(400, "invalid_participant", Grants::CAP_RANGE) unless cap.nil? || Grants.cap?(cap)
57
+
58
+ issued = Participants.invite(@grants, session_id: id, name: body["name"], kind: (body["kind"] || "human").to_s,
59
+ ttl: ttl, cap: cap, state_dir: default_state_dir)
60
+ link = participant_link(req, id, issued.token, expires_at: issued.grant.expires_at)
61
+ warning = ReviewStart.share_warning(Session.load(id, state_dir: default_state_dir))
62
+ json_response(201, { participant: issued.grant.public_h(@grants.now), token: issued.token,
63
+ link: link, lan: !@lan.nil? || !@public_url.nil?, qr_svg: QR.svg(link), warning: warning })
64
+ rescue Grants::Invalid => e
65
+ error_response(400, "invalid_participant", e.message)
66
+ end
67
+
68
+ # GET /api/sessions/:id/apply[?turn=T] (owner): the owner's turn that
69
+ # applies review turn T's proposal (ReviewApply: the reply quoted
70
+ # under one line of the owner's), for the composer: never sent from
71
+ # here. Without turn, the latest review turn with a reply. Read from
72
+ # the live worker's messages, else the saved ones.
73
+ # @return 200 {text, turn_id, author, author_name}; 404 not_found (no
74
+ # such turn, or no review turn); 400 not_review_turn; 409 no_reply
75
+ def handle_apply(req, id)
76
+ session = @session_class.load(id, state_dir: default_state_dir)
77
+ live = bridge_get_json(id, "snapshot")
78
+ messages = live_or_saved(live && live["snapshot"], "messages") { session.messages }
79
+ proposal = ReviewApply.find(messages, req.params["turn"])
80
+ json_response(200, { text: ReviewApply.compose(proposal), turn_id: proposal.turn_id, author: proposal.author,
81
+ author_name: proposal.author_name })
82
+ rescue ReviewApply::Refused => e
83
+ status = { not_found: 404, not_review_turn: 400, no_reply: 409 }.fetch(e.code)
84
+ error_response(status, e.code.to_s, e.message)
85
+ end
86
+
87
+ # DELETE /api/sessions/:id/participants[?id=p_…], DELETE
88
+ # /api/participants: revokes one participant, a session's or every
89
+ # one's; their open streams end within a poll.
90
+ def handle_participants_revoke(req, id = nil)
91
+ grant_id = req.params["id"]
92
+ if grant_id && !Grants::ID_RE.match?(grant_id.to_s)
93
+ return error_response(400, "invalid_participant", "not a participant id: #{grant_id.to_s[0, 40]}")
94
+ end
95
+
96
+ revoked = Participants.revoke(@grants, session_id: id, id: grant_id, by: "owner", state_dir: default_state_dir)
97
+ now = @grants.now
98
+ json_response(200, { revoked: revoked.map { |grant| grant.public_h(now) } })
99
+ end
100
+
101
+ # POST /api/sessions/:id/participants/:participant/cap {cap}: the
102
+ # active participant's new spending cap (dollars), from their next
103
+ # turn on. 200 {participant}; 400 invalid_participant.
104
+ def handle_participants_cap(req, id, grant_id)
105
+ body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
106
+ unless Grants::ID_RE.match?(grant_id.to_s)
107
+ return error_response(400, "invalid_participant", "not a participant id: #{grant_id.to_s[0, 40]}")
108
+ end
109
+
110
+ grant = Participants.set_cap(@grants, session_id: id, id: grant_id, cap: body["cap"], state_dir: default_state_dir)
111
+ return error_response(400, "invalid_participant", Participants.no_participant(grant_id, id)) unless grant
112
+
113
+ json_response(200, { participant: grant.public_h(@grants.now) })
114
+ rescue Grants::Invalid => e
115
+ error_response(400, "invalid_participant", e.message)
116
+ end
117
+
118
+ # The link a participant opens: web.public_url's with a one-time code
119
+ # for the token in the fragment (LinkCodes, until the grant expires;
120
+ # the page trades it, POST /api/token); else this chi web's LAN address
121
+ # when it has one (the owner may be asking on loopback), else the Host
122
+ # asked; the token traded for the cookie, the session in the fragment.
123
+ def participant_link(req, id, token, expires_at: nil)
124
+ if @public_url
125
+ ttl = expires_at ? [Time.iso8601(expires_at) - @grants.now, 1].max : LinkCodes::OWNER_TTL
126
+ return @public_url.link(@link_codes.issue(kind: :grant, token: token, ttl: ttl), "s=#{id}")
127
+ end
128
+
129
+ host = req.get_header("HTTP_HOST").to_s
130
+ port = host[/:(\d+)\z/, 1] || req.port.to_s
131
+ name = @lan ? @lan[:ip] : host.sub(/:\d*\z/, "")
132
+ "http://#{name}:#{port}/?token=#{token}#s=#{id}"
133
+ end
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,174 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "link_codes"
4
+ require_relative "principal"
5
+ require_relative "public_url"
6
+ require_relative "../log"
7
+ require_relative "../proxy_trace"
8
+
9
+ module Samagotchi
10
+ module Web
11
+ # chi web behind an auth proxy (web.public_url), mixed into App. With a
12
+ # PublicUrl every request needs a token (this machine's too: a proxy
13
+ # with no trace and a rewritten Host looks local). A request is
14
+ # *proxied* when it carries a proxy trace (ProxyTrace: X-Forwarded-*,
15
+ # Forwarded, X-Real-IP, a known identity header…), the configured
16
+ # identity header, or the public Host. A proxied request:
17
+ # - is the owner with the owner token, and, when web.proxy.identity_header
18
+ # is set, only if that header is one clean value equal to
19
+ # web.proxy.owner (D-a: identity AND token);
20
+ # - is a participant with a live grant's token (a grant bound to an
21
+ # identity only for that identity, and only proxied);
22
+ # - else nil: the gate's 401, its reason in the detail (only the
23
+ # requester's own identity) and the log.
24
+ # The identity header is refused when repeated, with a comma, empty, or
25
+ # sent under two names or with an underscore: WEBrick folds
26
+ # X_Forwarded_Email into the same Rack key as X-Forwarded-Email, the
27
+ # last one winning, so the gate reads the raw names (RawHeaderNames,
28
+ # installed by Server). See docs/configuration.md "Behind an auth proxy".
29
+ module ProxyGate
30
+ # The header names a request came with, as WEBrick read them
31
+ # (lower-cased, "_" kept), in the Rack env. Prepended to
32
+ # WEBrick::HTTPRequest by Server.
33
+ module RawHeaderNames
34
+ def meta_vars
35
+ super.merge(RAW_NAMES_ENV => header.keys)
36
+ end
37
+ end
38
+
39
+ RAW_NAMES_ENV = "samagotchi.raw_header_names"
40
+ # Why the gate refused a proxied request, for the 401's detail.
41
+ REFUSED_ENV = "samagotchi.proxy_refused"
42
+ # The token cookie on a proxied (https) request: Secure, Path=/, no
43
+ # Domain (other host names under the domain, a pod's other ports, don't
44
+ # get it). Cookies aren't port-scoped: a server on the same host name
45
+ # and another port does.
46
+ SECURE_COOKIE = "__Host-chi_token"
47
+
48
+ private
49
+
50
+ def init_proxy_gate(public_url, token)
51
+ @public_url = public_url
52
+ @public_token = token
53
+ @link_codes = LinkCodes.for_grants(@grants.path)
54
+ @proxy_hint_mutex = Mutex.new
55
+ @proxy_hint_logged = false
56
+ end
57
+
58
+ def proxied?(req)
59
+ return false unless @public_url
60
+
61
+ env = req.env
62
+ return true if @public_url.host?(env["HTTP_HOST"])
63
+ return true if @public_url.identity_env && env.key?(@public_url.identity_env)
64
+
65
+ names = env[RAW_NAMES_ENV] || env.keys.filter_map { |key| ProxyTrace.env_name(key) }
66
+ names.any? { |name| ProxyTrace.header?(name) }
67
+ end
68
+
69
+ # [:ok, email] | [:none, nil] | [:bad, reason]: the configured identity
70
+ # header of a proxied request; :none without one configured.
71
+ def proxy_identity(req)
72
+ env_key = @public_url.identity_env
73
+ return [:none, nil] unless env_key
74
+
75
+ raw = req.env[RAW_NAMES_ENV]
76
+ return [:bad, "the server gave no raw header names to check the identity header against"] unless raw
77
+
78
+ names = raw.select { |name| PublicUrl.env_key(name) == env_key }.uniq
79
+ return [:bad, "identity header sent under #{names.size} names (#{names.join(", ")})"] if names.size > 1
80
+ return [:bad, "identity header sent with an underscore (#{names.first})"] if names.first&.include?("_")
81
+
82
+ value = req.env[env_key]
83
+ return [:none, nil] if value.nil?
84
+ return [:bad, "identity header not among the raw header names"] if names.empty?
85
+
86
+ value = value.strip
87
+ return [:bad, "identity header empty"] if value.empty?
88
+ return [:bad, "identity header repeated or with a comma"] if value.include?(",")
89
+
90
+ [:ok, value.downcase]
91
+ end
92
+
93
+ # The principal of a proxied request, or nil (the reason in the env).
94
+ def proxied_principal(req, given)
95
+ state, identity = proxy_identity(req)
96
+ return proxy_refuse(req, identity) if state == :bad
97
+
98
+ notice_identity_headers(req) if state == :none
99
+ shown = identity || "(none)"
100
+ if owner_token?(given)
101
+ return Principal::OWNER if @public_url.identity_env.nil?
102
+ return Principal::OWNER if @public_url.owner && identity == @public_url.owner
103
+
104
+ return proxy_refuse(req, "owner token with identity #{shown}#{identity_hint(req)}")
105
+ end
106
+ grant_tokens = given.select { |value| Grants.token?(value) }
107
+ return proxy_refuse(req, "no token (identity #{shown})") if grant_tokens.empty?
108
+
109
+ participant_principal(req, grant_tokens, identity: identity, proxied: true)
110
+ end
111
+
112
+ # chi's own probe of a chi web behind a proxy (InfoProbe: a second chi
113
+ # web, chi share, chi update) sends no token: GET /api/info from this
114
+ # machine, not through the proxy, with no token at all, gets the
115
+ # fields it checks (nothing secret), so no probe ever hands the token
116
+ # to whatever listens on the port.
117
+ def probe_info?(req)
118
+ return false unless @public_url && req.get? && req.path_info == "/api/info"
119
+ return false unless App::LOOPBACK_PEERS.include?(req.get_header("REMOTE_ADDR").to_s) && !proxied?(req)
120
+
121
+ req.get_header("HTTP_AUTHORIZATION").nil? && req.get_header("HTTP_COOKIE").nil?
122
+ end
123
+
124
+ def probe_info
125
+ json_response(200, { app: "chi-web", version: Samagotchi::VERSION, pid: Process.pid, features: App::INFO_FEATURES,
126
+ lan: @lan && @lan[:ip] })
127
+ end
128
+
129
+ def proxy_refuse(req, reason)
130
+ req.env[REFUSED_ENV] = reason
131
+ nil
132
+ end
133
+
134
+ # The known identity headers (ProxyTrace::IDENTITY_HEADERS) a proxied
135
+ # request carries other than the configured one.
136
+ def other_identity_headers(req)
137
+ ProxyTrace::IDENTITY_HEADERS.select do |name|
138
+ key = PublicUrl.env_key(name)
139
+ key != @public_url.identity_env && req.env.key?(key)
140
+ end
141
+ end
142
+
143
+ def identity_hint(req)
144
+ return "" if @public_url.identity_env.nil? || req.env.key?(@public_url.identity_env)
145
+
146
+ others = other_identity_headers(req)
147
+ others.empty? ? "" : "; the proxy sends #{others.join(", ")}, not #{@public_url.identity_header}"
148
+ end
149
+
150
+ # Once per start: a proxied request without the configured identity
151
+ # header (or with none configured) but with a header a known setup
152
+ # puts the identity in. A wrong header locks the owner out, and one the
153
+ # proxy doesn't replace is a client-chosen string: the line says which.
154
+ def notice_identity_headers(req)
155
+ return if @proxy_hint_logged
156
+
157
+ others = other_identity_headers(req)
158
+ return if others.empty?
159
+ return unless @proxy_hint_mutex.synchronize { !@proxy_hint_logged && (@proxy_hint_logged = true) }
160
+
161
+ if @public_url.identity_env
162
+ Log.warn(:web, "proxy_identity_header", configured: @public_url.identity_header, sent: others.join(","),
163
+ echo: "Warning: chi web: the proxy sends #{others.join(", ")}, not " \
164
+ "web.proxy.identity_header #{@public_url.identity_header}")
165
+ else
166
+ Log.info(:web, "proxy_identity_header", configured: "none", sent: others.join(","),
167
+ echo: "chi web: the proxy sends #{others.join(", ")}; with " \
168
+ "web.proxy.identity_header and web.proxy.owner it is checked " \
169
+ "next to the token (only a header the proxy replaces)")
170
+ end
171
+ end
172
+ end
173
+ end
174
+ end
@@ -24,7 +24,10 @@ import {
24
24
  addContext,
25
25
  renderText,
26
26
  getWorkingSet,
27
+ onAuthLost,
27
28
  } from "./data.js";
29
+ import { authProbe, createAuthLost } from "./auth_lost.js";
30
+ import { REPLACE_SESSION_TEXT, fragmentCode, tradeFragmentCode } from "./token_fragment.js";
28
31
  import { createContextChips } from "./context_chips.js";
29
32
  import { createLlmContextControl } from "./llm_context_chip.js";
30
33
  import { createParticipantsControl } from "./participants_panel.js";
@@ -96,6 +99,16 @@ import { createSessionActions } from "./session_actions.js";
96
99
  import { createRename } from "./session_rename.js";
97
100
  import { createSendTurn } from "./send_turn.js";
98
101
 
102
+ // A link's #code= (behind an auth proxy): traded for the cookie before
103
+ // anything else runs; the page reloads without it.
104
+ // This page has a session already: the trade would replace it (a link
105
+ // someone sent to swap this browser's session for theirs), so ask first.
106
+ if (fragmentCode(globalThis.location?.hash)
107
+ && await tradeFragmentCode({ ask: () => globalThis.confirm(REPLACE_SESSION_TEXT) })) await new Promise(() => {});
108
+ // Signed out (the proxy's session or chi's token): a banner, or one reload.
109
+ const authLost = createAuthLost();
110
+ onAuthLost(authLost);
111
+
99
112
  const $ = (s) => document.querySelector(s);
100
113
  const topStripEl = $("#topStrip");
101
114
  const allListEl = $("#allList");
@@ -449,9 +462,20 @@ function openSessionEvents() {
449
462
  eventsControl = null;
450
463
  refresh();
451
464
  },
465
+ // The browser gave up after frames: signed out (the proxy's sign-in
466
+ // page answered the reconnect), or chi web went away for a while.
467
+ onClosed: () => {
468
+ eventsControl = null;
469
+ authProbe().then((state) => {
470
+ if (state === "lost") authLost("events");
471
+ else setTimeout(openSessionEvents, EVENTS_REOPEN_MS);
472
+ });
473
+ },
452
474
  });
453
475
  }
454
476
 
477
+ const EVENTS_REOPEN_MS = 3000;
478
+
455
479
  // Which chi serves this page now and which is the newest installed (the
456
480
  // events snapshot, and `chi` frames when that changes). A toast says when
457
481
  // chi web was upgraded while this tab stayed open (offering the reload,
@@ -0,0 +1,76 @@
1
+ // Signed out: the auth proxy's session (Okta…) or chi's token is gone. An
2
+ // /api answer says so in one of these ways: a 401 (chi's unauthorized, or
3
+ // the proxy's own 401 {} for Accept: application/json), a fetch that was
4
+ // redirected or came back as HTML (a sign-in page), or, from the probe,
5
+ // a redirect fetch can't follow (real IdPs send no CORS: a TypeError, so
6
+ // the probe asks with redirect: "manual"). The page then says so in a
7
+ // banner with Reload, and reloads by itself at most once a minute (the
8
+ // proxy's sign-in brings the user back), never when it can't keep the time.
9
+
10
+ export const AUTH_RELOAD_KEY = "chi.authReloadAt";
11
+ export const AUTH_RELOAD_MS = 60_000;
12
+
13
+ // Whether a fetch Response says the sign-in is gone.
14
+ export function lostAnswer(res) {
15
+ if (!res) return false;
16
+ if (res.status === 401 || res.redirected || res.type === "opaqueredirect") return true;
17
+ const type = res.headers?.get?.("content-type") || "";
18
+ return type.includes("text/html");
19
+ }
20
+
21
+ // "lost" | "ok" | "down" (chi web unreachable: no banner, the page's own
22
+ // retries go on).
23
+ export async function authProbe(fetchImpl = globalThis.fetch) {
24
+ try {
25
+ const res = await fetchImpl("/api/info", {
26
+ credentials: "same-origin", redirect: "manual", headers: { Accept: "application/json" },
27
+ });
28
+ return lostAnswer(res) ? "lost" : "ok";
29
+ } catch (_) {
30
+ return "down";
31
+ }
32
+ }
33
+
34
+ export const AUTH_LOST_TEXT = "Signed out (the proxy's sign-in or chi's token ended).";
35
+
36
+ // The page's authLost(reason): once, a banner (doc) and, unless one ran in
37
+ // the last minute, a reload. storage: sessionStorage (may be missing or throw).
38
+ export function createAuthLost({
39
+ doc = globalThis.document, storage = () => globalThis.sessionStorage, reload = () => globalThis.location.reload(),
40
+ now = () => Date.now(), log = (reason) => console.warn("chi: signed out", reason),
41
+ } = {}) {
42
+ let shown = false;
43
+ return function authLost(reason) {
44
+ if (shown) return;
45
+ shown = true;
46
+ log(reason);
47
+ // The reload only when its stamp can be kept: without storage (a
48
+ // private window) a page that keeps losing its sign-in would reload
49
+ // forever, so it gets the banner.
50
+ let due = false;
51
+ try {
52
+ due = now() - (Number(storage().getItem(AUTH_RELOAD_KEY)) || 0) >= AUTH_RELOAD_MS;
53
+ if (due) storage().setItem(AUTH_RELOAD_KEY, String(now()));
54
+ } catch (_) {
55
+ due = false;
56
+ }
57
+ if (due) {
58
+ reload();
59
+ return;
60
+ }
61
+ const bar = doc.createElement("div");
62
+ bar.id = "authLost";
63
+ bar.setAttribute("role", "alert");
64
+ bar.style.cssText = "position:fixed;top:0;left:0;right:0;z-index:10000;padding:8px 16px;font-size:14px;"
65
+ + "color:var(--warn-text);background:var(--warn-bg);border-bottom:1px solid var(--warn-border);"
66
+ + "display:flex;gap:12px;align-items:center;justify-content:center";
67
+ const text = doc.createElement("span");
68
+ text.textContent = AUTH_LOST_TEXT;
69
+ const button = doc.createElement("button");
70
+ button.type = "button";
71
+ button.textContent = "Reload";
72
+ button.addEventListener("click", () => reload());
73
+ bar.append(text, button);
74
+ doc.body.append(bar);
75
+ };
76
+ }