tensaku 0.0.1 → 0.2.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.
@@ -2,37 +2,34 @@ require "json"
2
2
  require "digest"
3
3
 
4
4
  module Tensaku
5
- # The JSON endpoints the overlay talks to, plus the overlay script and the MCP endpoint. Everything
6
- # except the script needs a loopback address, and everything the overlay calls needs the boot token.
5
+ # The JSON endpoints the overlay talks to, plus the overlay script. Everything needs a loopback
6
+ # address, and everything except the script needs the boot token. Agents don't come through here:
7
+ # `tensaku mcp` works on the database directly.
7
8
  class Endpoints
8
9
  ASSET = File.expand_path("../../app/assets/tensaku.js", __dir__)
9
10
 
11
+ # Edit mode asks about every stamp on the page at once.
12
+ EDITABLE_LIMIT = 5000
13
+
14
+ # An event stream waits on the doorbell, and checks anyway this often: for an agent that stopped
15
+ # checking in, and to write a comment so a closed tab is noticed.
16
+ STREAM_CHECK = 10
17
+
18
+ # /notes/ID and /notes/ID/screenshot.
19
+ NOTE_PATH = %r{\A/notes/([a-z0-9]+)(?:/screenshot)?\z}
20
+
10
21
  def self.asset_digest
11
22
  Digest::SHA256.file(ASSET).hexdigest[0, 12]
12
23
  rescue Errno::ENOENT
13
24
  "missing"
14
25
  end
15
26
 
16
- # What the overlay last selected, for the MCP `current_selection` tool. One person, one browser.
17
- def self.selection
18
- @selection
19
- end
20
-
21
- def self.selection=(value)
22
- @selection = value
23
- end
24
-
25
27
  def call(env)
26
28
  request = Rack::Request.new(env)
27
29
  path = request.path_info.delete_prefix(Tensaku.config.mount_path)
28
30
 
29
31
  return script(request) if path == "/tensaku.js" && request.get?
30
32
 
31
- if path == "/mcp"
32
- Guard.check_local_client!(request)
33
- return Mcp.new.call(request)
34
- end
35
-
36
33
  Guard.check_request!(request)
37
34
  route(request, path)
38
35
  rescue Forbidden => error
@@ -41,58 +38,146 @@ module Tensaku
41
38
  json({ error: error.message, stale: true }, 409)
42
39
  rescue Notes::NotFound => error
43
40
  json({ error: error.message }, 404)
44
- rescue Error, JSON::ParserError => error
41
+ rescue Error, JSON::ParserError, ArgumentError, TypeError => error
45
42
  json({ error: error.message }, 422)
43
+ rescue StandardError => error
44
+ # Tensaku sits in front of Rails' exception pages, so it logs and answers for itself.
45
+ Rails.logger.error("[Tensaku] #{error.class}: #{error.message}\n#{Array(error.backtrace).first(10).join("\n")}")
46
+ json({ error: "Tensaku hit an error: #{error.class}: #{error.message}. The server log has the details." }, 500)
46
47
  end
47
48
 
48
49
  private
49
50
 
50
51
  def route(request, path)
51
52
  params = request.get? ? request.GET : body(request)
53
+ note_id = path[NOTE_PATH, 1]
52
54
 
53
55
  case [ request.request_method, path ]
54
56
  in [ "GET", "/source" ]
55
57
  template, line, column = Source::Template.from_stamp(params["stamp"])
56
58
  json(template.describe(line, column))
59
+ in [ "POST", "/editable" ]
60
+ stamps = Array(params["stamps"]).map(&:to_s).uniq
61
+ raise Error, "Too many stamps (#{stamps.size}); the limit is #{EDITABLE_LIMIT}" if stamps.size > EDITABLE_LIMIT
62
+ json(editable: Source::Template.editable(stamps))
57
63
  in [ "POST", "/text" ]
58
- template, line, column = Source::Template.from_stamp(params["stamp"])
59
- edits = Array(params["edits"]).map { it.to_h.symbolize_keys }
60
- written(template.edit_text(line, column, edits), :template)
64
+ edits = Array(params["edits"]).map { object!(it, "An edit").symbolize_keys }
65
+ written(:template) do
66
+ template, line, column = Source::Template.from_stamp(params["stamp"])
67
+ template.edit_text(line, column, edits)
68
+ end
61
69
  in [ "POST", "/attribute" ]
62
- template, line, column = Source::Template.from_stamp(params["stamp"])
63
- written(template.edit_attribute(line, column, params["name"].to_s, params.to_h.symbolize_keys), :template)
70
+ written(:template) do
71
+ template, line, column = Source::Template.from_stamp(params["stamp"])
72
+ template.edit_attribute(line, column, params["name"].to_s, params.to_h.symbolize_keys)
73
+ end
64
74
  in [ "GET", "/translation" ]
65
75
  json(key: params["key"], locales: Source::Locale.lookup_all(params["key"].to_s))
66
76
  in [ "POST", "/translation" ]
67
- result = Source::Locale.edit(params["locale"].to_s, params["key"].to_s, original: params["original"], text: params["text"])
68
- written(result, :locale)
77
+ written(:locale) { Source::Locale.edit(params["locale"].to_s, params["key"].to_s, original: params["original"], text: params["text"]) }
69
78
  in [ "GET", "/markdown" ]
70
79
  json(Source::Markdown.new(params["range"]).describe(tag: params["tag"]))
71
80
  in [ "POST", "/markdown" ]
72
- written(Source::Markdown.new(params["range"]).edit(original: params["original"], text: params["text"]), :markdown)
81
+ written(:markdown) { Source::Markdown.new(params["range"]).edit(original: params["original"], text: params["text"], tag: params["tag"]) }
73
82
  in [ "GET", "/notes" ]
74
- Notes.prune!
75
- json(notes: Notes.list(url: params["url"].presence, status: params["status"].presence), open: Notes.list(status: %w[open question]).size)
83
+ visited(request)
84
+ # restart: Tensaku's code changed since this server started, so it answers with the old code
85
+ # while the page runs the new overlay script.
86
+ # archived=1 lists the archive instead, for the notes panel's Archive tab.
87
+ listed = Notes.list(url: params["url"].presence, status: ("archived" if params["archived"] == "1"))
88
+ # changed_at: the last time an agent said something on a note in this app, so the page fetches
89
+ # itself again to show its change, whatever page the note was on.
90
+ json(notes: listed, open: Notes.active_count, agents: Agents.list, restart: Build.stale?, changed_at: Notes.last_agent_message_at)
91
+ in [ "GET", "/events" ]
92
+ events(request)
76
93
  in [ "GET", "/notes.md" ]
77
- notes = params["id"].present? ? [ Notes.find(params["id"]) ] : Notes.list(url: params["url"].presence, status: params["status"].presence || %w[open question])
78
- [ 200, { "content-type" => "text/markdown; charset=utf-8" }, [ Notes.to_markdown(notes) ] ]
94
+ notes = Notes.list(url: params["url"].presence, status: Notes::ACTIVE)
95
+ markdown = params["format"] == "short" ? Notes::Markdown.short(notes) : Notes::Markdown.list(notes)
96
+ [ 200, { "content-type" => "text/markdown; charset=utf-8" }, [ markdown ] ]
79
97
  in [ "POST", "/notes" ]
80
98
  json(Notes.create(params), 201)
81
- in [ "PATCH", %r{\A/notes/([a-z0-9]+)\z} ]
82
- id = path.split("/").last
83
- json(Notes.update(id, status: params["status"], reply: params["reply"], comment: params["comment"]))
84
- in [ "DELETE", %r{\A/notes/([a-z0-9]+)\z} ]
85
- Notes.delete(path.split("/").last)
99
+ in [ "PUT", %r{\A/notes/[a-z0-9]+/screenshot\z} ]
100
+ json(Notes.attach_screenshot(note_id, params["png"]))
101
+ in [ "GET", %r{\A/notes/[a-z0-9]+/screenshot\z} ]
102
+ shot = Notes.screenshot(note_id) or raise Notes::NotFound, "That note has no screenshot"
103
+ [ 200, { "content-type" => "image/png", "cache-control" => "no-store" }, [ shot["png"] ] ]
104
+ in [ "PATCH", %r{\A/notes/[a-z0-9]+\z} ]
105
+ # An edit or a message is for the agent: the note is sent again. A status change alone (done,
106
+ # reopened, or undoing either) isn't.
107
+ changed = params["message"].present? || params["comment"].present?
108
+ json(Notes.update(note_id, status: params["status"], comment: params["comment"],
109
+ message: params["message"], from: "you", send: changed && params["status"] == "open", to: params["to"]))
110
+ in [ "POST", "/notes/archive" ]
111
+ json(archived: Notes.archive!(params["ids"]))
112
+ in [ "DELETE", %r{\A/notes/[a-z0-9]+\z} ]
113
+ Notes.delete(note_id)
86
114
  json({ deleted: true })
115
+ in [ "GET", "/editor" ]
116
+ json(url: editor_url(params["file"], params["line"]))
87
117
  in [ "POST", "/selection" ]
88
- self.class.selection = params.to_h.slice("url", "targets", "text").merge("at" => Time.now.utc.iso8601)
118
+ Project.select!(params.to_h.slice("url", "targets", "text"), tab: params["tab"])
89
119
  json({ ok: true })
90
120
  else
91
121
  json({ error: "Not found" }, 404)
92
122
  end
93
123
  end
94
124
 
95
- def written(result, kind)
125
+ # Server-sent events: one "changed" event whenever the notes or the agents change (Project.version),
126
+ # and one right away, so the page loads the notes when told instead of asking every few seconds.
127
+ # The stream sleeps on the doorbell until a write rings it.
128
+ # The connection is taken over from the web server (Rack hijack) and served from a thread of its
129
+ # own, so an open tab doesn't hold one of the server's threads. A server without hijack answers
130
+ # 501, and the page polls instead.
131
+ def events(request)
132
+ hijack = request.env["rack.hijack"]
133
+ return json({ error: "This web server can't stream events" }, 501) unless hijack
134
+
135
+ visited(request)
136
+ io = hijack.call
137
+ root = Tensaku.root
138
+ Thread.new { Tensaku.with_root(root) { stream(io) } }
139
+ [ -1, {}, [] ]
140
+ end
141
+
142
+ def stream(io)
143
+ Doorbell.listen(Tensaku.root) do |doorbell|
144
+ io.write("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncache-control: no-store\r\nconnection: close\r\n\r\n")
145
+ last = nil
146
+ loop do
147
+ version = Project.version
148
+ io.write(version == last ? ": ping\n\n" : "data: changed\n\n")
149
+ io.flush
150
+ last = version
151
+ doorbell.wait(STREAM_CHECK)
152
+ end
153
+ end
154
+ rescue IOError, SystemCallError
155
+ nil # the tab closed
156
+ ensure
157
+ io.close unless io.closed?
158
+ end
159
+
160
+ # The page asks for its notes: archive the old ones, and keep the URL agents' links start with.
161
+ def visited(request)
162
+ Notes.prune!
163
+ Project.base_url = request.base_url
164
+ end
165
+
166
+ # A link that opens the file in the editor named by RAILS_EDITOR or EDITOR, through Rails' own
167
+ # list of editors, or nil when none is set.
168
+ def editor_url(file, line)
169
+ editor = ActiveSupport::Editor.current
170
+ return nil unless editor
171
+
172
+ path = Tensaku.root.join(file.to_s).expand_path
173
+ raise Error, "Not a file in this app: #{file}" unless path.to_s.start_with?(Tensaku.root.expand_path.to_s + "/") && path.file?
174
+
175
+ editor.url_for(path.to_s, line.to_i.clamp(1, 1_000_000))
176
+ end
177
+
178
+ # Reads, checks and writes the source under the write lock.
179
+ def written(kind)
180
+ result = FileWrite.locked { yield }
96
181
  Caches.clear!(kind) if result[:changed]
97
182
  json(result.merge(warning: Caches.fragment_cache_warning).compact)
98
183
  end
@@ -105,7 +190,13 @@ module Tensaku
105
190
 
106
191
  def body(request)
107
192
  raw = request.body&.read.to_s
108
- raw.empty? ? {} : JSON.parse(raw)
193
+ raw.empty? ? {} : object!(JSON.parse(raw), "The request body")
194
+ end
195
+
196
+ def object!(value, what)
197
+ raise Error, "#{what} must be a JSON object" unless value.is_a?(Hash)
198
+
199
+ value
109
200
  end
110
201
 
111
202
  def json(data, status = 200)
@@ -2,6 +2,25 @@ module Tensaku
2
2
  module FileWrite
3
3
  module_function
4
4
 
5
+ # Runs the block holding one lock shared by every thread and every process (the dev server and
6
+ # `tensaku mcp`), so two saves can't both read a file, check it and then overwrite each other's change. Writers re-read the file
7
+ # inside the block. Nested calls in the same thread don't wait on themselves.
8
+ def locked
9
+ return yield if Thread.current[:tensaku_write_lock]
10
+
11
+ path = Tensaku.root.join("tmp/tensaku/write.lock")
12
+ path.dirname.mkpath
13
+ File.open(path, File::RDWR | File::CREAT, 0o644) do |file|
14
+ file.flock(File::LOCK_EX)
15
+ begin
16
+ Thread.current[:tensaku_write_lock] = true
17
+ yield
18
+ ensure
19
+ Thread.current[:tensaku_write_lock] = nil
20
+ end
21
+ end
22
+ end
23
+
5
24
  # Writes through a temp file in the same directory and renames it over the original, keeping the
6
25
  # file mode, so a crash can't leave half a file behind.
7
26
  def atomic(path, content)
@@ -29,5 +48,16 @@ module Tensaku
29
48
  end
30
49
  result.force_encoding(source.encoding)
31
50
  end
51
+
52
+ # The lines a write changed, for the overlay's save message: the first line's number, then the old
53
+ # and new lines between what the two versions share at each end.
54
+ def diff(before, after)
55
+ was, now = [ before, after ].map { it.dup.force_encoding(Encoding::UTF_8).scrub.lines(chomp: true) }
56
+ prefix = 0
57
+ prefix += 1 while prefix < was.size && prefix < now.size && was[prefix] == now[prefix]
58
+ suffix = 0
59
+ suffix += 1 while suffix < was.size - prefix && suffix < now.size - prefix && was[-1 - suffix] == now[-1 - suffix]
60
+ { line: prefix + 1, removed: was[prefix...(was.size - suffix)], added: now[prefix...(now.size - suffix)] }
61
+ end
32
62
  end
33
63
  end
data/lib/tensaku/guard.rb CHANGED
@@ -1,37 +1,44 @@
1
1
  require "ipaddr"
2
2
 
3
3
  module Tensaku
4
- # Every endpoint goes through here: loopback addresses only, the boot token for anything that reads
5
- # source or writes, and writes limited to the allow-list.
4
+ # Every endpoint goes through here: requests from this machine only, the boot token for anything
5
+ # that reads source or writes, and writes limited to the allow-list.
6
+ #
7
+ # "From this machine" means a loopback peer address, no proxy header naming another client, a Host
8
+ # that is a local name (or one the app lists in config.hosts), and no Origin from another site. The
9
+ # Host check stops DNS rebinding: a page on another domain that resolves to 127.0.0.1.
6
10
  module Guard
7
11
  LOOPBACK = [ IPAddr.new("127.0.0.0/8"), IPAddr.new("::1/128") ].freeze
12
+ FORWARDED = %w[HTTP_X_FORWARDED_FOR HTTP_X_REAL_IP HTTP_FORWARDED HTTP_CLIENT_IP HTTP_TRUE_CLIENT_IP HTTP_CF_CONNECTING_IP].freeze
8
13
 
9
14
  module_function
10
15
 
11
16
  def loopback?(request)
12
- address = request.get_header("REMOTE_ADDR").to_s
13
- LOOPBACK.any? { it.include?(IPAddr.new(address)) }
14
- rescue IPAddr::InvalidAddressError
17
+ loopback_address?(request.get_header("REMOTE_ADDR")) && !forwarded_from_elsewhere?(request)
18
+ end
19
+
20
+ # Whether the request came from this machine and from a page of this app, not another site.
21
+ def local_request?(request)
22
+ check_local_client!(request)
23
+ true
24
+ rescue Forbidden
15
25
  false
16
26
  end
17
27
 
18
28
  def check_request!(request)
19
- raise Forbidden, "Tensaku only answers requests from this machine" unless loopback?(request)
29
+ check_local_client!(request)
20
30
 
21
31
  token = request.get_header("HTTP_X_TENSAKU_TOKEN").to_s
22
32
  raise Forbidden, "Missing or wrong Tensaku token. Reload the page." unless secure_compare(token, Tensaku.token)
23
33
  end
24
34
 
25
- # MCP clients can't read the page token, so the MCP endpoint relies on loopback plus a check that
26
- # the request doesn't come from a web page (no foreign Origin, a local Host).
35
+ # Every endpoint but the script adds the token on top of this.
27
36
  def check_local_client!(request)
28
37
  raise Forbidden, "Tensaku only answers requests from this machine" unless loopback?(request)
29
38
 
30
39
  origin = request.get_header("HTTP_ORIGIN")
31
40
  raise Forbidden, "Cross-origin requests are refused" if origin && !local_url?(origin)
32
-
33
- host = request.host.to_s
34
- raise Forbidden, "Unexpected Host header" unless local_host?(host)
41
+ raise Forbidden, "Unexpected Host header" unless allowed_host?(raw_host(request))
35
42
  end
36
43
 
37
44
  # Resolves a path from the page (relative to Rails.root) to a real file inside the allow-list.
@@ -42,8 +49,7 @@ module Tensaku
42
49
  raise Forbidden, "#{relative} does not exist" unless path.file?
43
50
 
44
51
  real = path.realpath
45
- inside = writable_dirs.any? { real.to_s.start_with?("#{it}/") }
46
- raise Forbidden, "#{relative} is outside Tensaku's writable paths (#{Tensaku.config.writable_paths.join(", ")})" unless inside
52
+ raise Forbidden, "#{relative} is outside Tensaku's writable paths (#{Tensaku.config.writable_paths.join(", ")})" unless writable?(real)
47
53
 
48
54
  unless extensions.any? { real.basename.to_s.end_with?(it) }
49
55
  raise Forbidden, "#{relative} is not a #{extensions.join(" or ")} file"
@@ -52,26 +58,76 @@ module Tensaku
52
58
  real
53
59
  end
54
60
 
55
- # The configured paths, plus Kiln's content directory when Kiln's content layer is loaded.
61
+ # True for a real path inside a writable directory or equal to a writable file.
62
+ def writable?(real)
63
+ writable_dirs.any? { real.to_s.start_with?("#{it}/") } || writable_files.include?(real)
64
+ end
65
+
66
+ # The configured directories that exist.
56
67
  def writable_dirs
57
68
  dirs = Tensaku.config.writable_paths.map { Tensaku.root.join(it) }
58
- dirs << Pathname(Kiln::Content.root) if defined?(::Kiln::Content) && ::Kiln::Content.respond_to?(:root)
59
69
  dirs.select(&:directory?).map(&:realpath)
60
70
  end
61
71
 
72
+ # Single files from the configured paths, such as a README outside the app.
73
+ def writable_files
74
+ Tensaku.config.writable_paths.map { Tensaku.root.join(it) }.select(&:file?).map(&:realpath)
75
+ end
76
+
62
77
  def secure_compare(a, b)
63
78
  a.bytesize == b.bytesize && OpenSSL.fixed_length_secure_compare(a, b)
64
79
  end
65
80
 
81
+ def loopback_address?(address)
82
+ ip = IPAddr.new(address.to_s)
83
+ LOOPBACK.any? { it.include?(ip) }
84
+ rescue IPAddr::InvalidAddressError
85
+ false
86
+ end
87
+
88
+ # A proxy in front of the app (a tunnel, nginx) connects from 127.0.0.1 and names the real client
89
+ # in a header. Any client named there that isn't loopback means the request came from elsewhere.
90
+ def forwarded_from_elsewhere?(request)
91
+ FORWARDED.any? do |name|
92
+ value = request.get_header(name).to_s
93
+ next false if value.empty?
94
+
95
+ addresses = name == "HTTP_FORWARDED" ? value.scan(/for="?\[?([^\]";,\s]+)/i).flatten : value.split(",")
96
+ addresses.empty? || addresses.any? { !loopback_address?(it.strip.sub(/:\d+\z/, "")) }
97
+ end
98
+ end
99
+
100
+ # The Host header as sent, not request.host, which trusts X-Forwarded-Host.
101
+ def raw_host(request)
102
+ host = request.get_header("HTTP_HOST").to_s
103
+ host.start_with?("[") ? host[/\A\[[^\]]*\]/].to_s : host.sub(/:\d+\z/, "")
104
+ end
105
+
66
106
  def local_url?(url)
67
- local_host?(URI.parse(url).host.to_s)
107
+ allowed_host?(URI.parse(url).host.to_s)
68
108
  rescue URI::InvalidURIError
69
109
  false
70
110
  end
71
111
 
112
+ def allowed_host?(host)
113
+ local_host?(host) || app_host?(host)
114
+ end
115
+
72
116
  def local_host?(host)
73
- host = host.delete_prefix("[").delete_suffix("]")
117
+ host = host.to_s.delete_prefix("[").delete_suffix("]").downcase
74
118
  host == "localhost" || host.end_with?(".localhost") || (IPAddr.new(host).loopback? rescue false)
75
119
  end
120
+
121
+ # A name the app allows in config.hosts (for example a puma-dev .test domain). An empty list allows
122
+ # every host in Rails; here it allows none beyond the local names. IP ranges in the list don't count:
123
+ # Rails' development default allows every IP.
124
+ def app_host?(host)
125
+ return false if host.to_s.empty? || !defined?(Rails) || !Rails.application
126
+
127
+ hosts = Array(Rails.application.config.hosts).reject { it.is_a?(IPAddr) }
128
+ hosts.any? && ActionDispatch::HostAuthorization::Permissions.new(hosts).allows?(host)
129
+ rescue StandardError
130
+ false
131
+ end
76
132
  end
77
133
  end
data/lib/tensaku/i18n.rb CHANGED
@@ -44,6 +44,24 @@ module Tensaku
44
44
  text.include?(FENCE) ? text.gsub(PATTERN, "") : text
45
45
  end
46
46
 
47
+ # The raw value stored for the key, to tell a translation apart from a `default:` or a pluralized
48
+ # hash. A Chain backend asks each of its backends in order. A backend without its own lookup (one
49
+ # that only implements translate) gives nil, so its strings get no marker.
50
+ def stored_value(backend, locale, key, options)
51
+ if defined?(::I18n::Backend::Chain) && backend.is_a?(::I18n::Backend::Chain)
52
+ backend.backends.each do |inner|
53
+ value = stored_value(inner, locale, key, options)
54
+ return value unless value.nil?
55
+ end
56
+ return nil
57
+ end
58
+ return nil if backend.method(:lookup).owner == ::I18n::Backend::Base
59
+
60
+ backend.send(:lookup, locale, key, options[:scope], options)
61
+ rescue NameError, NotImplementedError
62
+ nil
63
+ end
64
+
47
65
  # Added to the app's I18n backend with `extend`, so it wraps whichever backend the app uses.
48
66
  module Backend
49
67
  def translate(locale, key, options = ::I18n::EMPTY_HASH)
@@ -52,7 +70,7 @@ module Tensaku
52
70
 
53
71
  full = ::I18n.normalize_keys(nil, key, options[:scope], options[:separator]).join(".")
54
72
  return result if full.match?(SKIP)
55
- return result unless lookup(locale, key, options[:scope], options).is_a?(String)
73
+ return result unless I18nMarkers.stored_value(self, locale, key, options).is_a?(String)
56
74
 
57
75
  marked = result + I18nMarkers.encode(locale, full)
58
76
  result.html_safe? ? marked.html_safe : marked