runlight 0.4.3 → 0.5.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 (44) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +1 -1
  4. data/assets/build.json +4 -4
  5. data/assets/dashboard.js +12 -12
  6. data/assets/locales.json +5 -5
  7. data/assets/picker.js +1 -1
  8. data/assets/tracker.js +1 -1
  9. data/lib/runlight/accounts/accounts.rb +40 -10
  10. data/lib/runlight/accounts/crypto.rb +6 -3
  11. data/lib/runlight/accounts/lockout.rb +98 -0
  12. data/lib/runlight/accounts/throttle.rb +70 -16
  13. data/lib/runlight/accounts/web.rb +71 -28
  14. data/lib/runlight/body.rb +13 -0
  15. data/lib/runlight/core.rb +194 -28
  16. data/lib/runlight/data/sources.rb +1 -2
  17. data/lib/runlight/db/connect.rb +2 -2
  18. data/lib/runlight/db/db.rb +52 -32
  19. data/lib/runlight/geo.rb +2 -2
  20. data/lib/runlight/http/response.rb +22 -3
  21. data/lib/runlight/icon.rb +2 -1
  22. data/lib/runlight/importers/csv_visits.rb +13 -3
  23. data/lib/runlight/importers/dub.rb +2 -1
  24. data/lib/runlight/importers/index.rb +2 -1
  25. data/lib/runlight/importers/umami.rb +3 -0
  26. data/lib/runlight/importers/visits.rb +16 -5
  27. data/lib/runlight/importers/write.rb +50 -12
  28. data/lib/runlight/links.rb +10 -1
  29. data/lib/runlight/mcp.rb +10 -1
  30. data/lib/runlight/oauth.rb +34 -23
  31. data/lib/runlight/payload.rb +26 -7
  32. data/lib/runlight/rack_app.rb +7 -1
  33. data/lib/runlight/routes.rb +51 -21
  34. data/lib/runlight/server/cli.rb +9 -0
  35. data/lib/runlight/server/db_ip.rb +287 -45
  36. data/lib/runlight/server/standalone.rb +41 -5
  37. data/lib/runlight/sources.rb +3 -2
  38. data/lib/runlight/store/sql.rb +14 -0
  39. data/lib/runlight/store/sql_store.rb +88 -59
  40. data/lib/runlight/ua.rb +14 -4
  41. data/lib/runlight/version.rb +1 -1
  42. data/lib/runlight/weak_keys.rb +31 -0
  43. data/lib/runlight.rb +2 -0
  44. metadata +6 -4
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "fileutils"
4
4
  require "net/http"
5
+ require "openssl"
5
6
  require "uri"
6
7
  require "zlib"
7
8
 
@@ -13,14 +14,51 @@ module Runlight
13
14
  # refresh(), and lookups read the newest file on disk. lookup() opens it at the first lookup, as each PHP
14
15
  # request does; a server that keeps running reads through current() instead, which load_newest() points at the
15
16
  # newest release whenever the schedule runs, as the Node server's Geo does.
17
+ #
18
+ # A download is used only once it is checked: its SHA-1 against the one DB-IP publishes on its download page,
19
+ # and the file itself as a DB-IP database of the kind asked for, no older than the one in use. That catches a
20
+ # damaged or swapped file, and a download server serving something else. It is not a signature: DB-IP
21
+ # publishes none, so whoever can change DB-IP's own page can change both. A checksum that does not match
22
+ # always refuses the download. Only when none can be read at all (the page is down, or no longer reads as it
23
+ # did) is a download accepted on the other checks alone, with a warning, so a change to that page does not
24
+ # stop location data everywhere.
16
25
  class DbIp
17
- # dir: the folder the releases live in. mode: "city" or "country". download: a callable taking the URL and a
18
- # file, that writes the gzipped file at the URL to the file and says whether it got one (Net::HTTP by
19
- # default). log: a callable taking a line.
20
- def initialize(dir, mode, download = nil, log = nil)
26
+ # How long after a first failed try the next one waits, and the longest any waits.
27
+ FIRST_WAIT = 5 * 60_000
28
+ LONGEST_WAIT = 6 * 3_600_000
29
+ # The most a database may unpack to, several times the city file's size, so a bad download cannot fill the disk.
30
+ MOST_BYTES = 512 * 1024 * 1024
31
+ # The most the download itself may weigh, and the least a database unpacks to (the country one is 8 MB).
32
+ MOST_PACKED_BYTES = 256 * 1024 * 1024
33
+ FEWEST_BYTES = 1024 * 1024
34
+ # The most of DB-IP's download page that is read; it is about 25 KB.
35
+ MOST_PAGE_BYTES = 1024 * 1024
36
+ DAY = 86_400_000
37
+ # A release is built at the start of its month and stands in until the next appears, so one is two months old at most.
38
+ OLDEST_BUILD = 100 * DAY
39
+ # Addresses any location database knows: Google's and Cloudflare's resolvers, over IPv4 and IPv6.
40
+ KNOWN = ["8.8.8.8", "1.1.1.1", "2001:4860:4860::8888"].freeze
41
+ MARKER = "\xAB\xCD\xEFMaxMind.com".b.freeze
42
+ private_constant :FIRST_WAIT, :LONGEST_WAIT, :MOST_BYTES, :MOST_PACKED_BYTES, :FEWEST_BYTES, :MOST_PAGE_BYTES, :DAY, :OLDEST_BUILD, :KNOWN, :MARKER
43
+
44
+ # An answer that was not a plain 200, with its status, so a month not out yet (404) can be told apart.
45
+ class Refused < StandardError
46
+ attr_reader :status
47
+
48
+ def initialize(status)
49
+ super("it answered #{status}")
50
+ @status = status
51
+ end
52
+ end
53
+
54
+ # dir: the folder the releases live in. mode: "city" or "country". get: a callable taking a URL and a
55
+ # timeout in seconds, that makes one GET without following any redirect and yields the status, the
56
+ # headers (a Hash with lowercase names), and the body as something whose each gives its parts; it returns
57
+ # what the block returns (Net::HTTP by default). log: a callable taking a line.
58
+ def initialize(dir, mode, get = nil, log = nil)
21
59
  @dir = dir
22
60
  @mode = mode
23
- @download = download || method(:fetch_to)
61
+ @get = get || method(:http_get)
24
62
  @log = log || ->(line) { warn(line) }
25
63
  @loaded = nil
26
64
  @lookup = nil
@@ -32,6 +70,68 @@ module Runlight
32
70
  Time.at(ms.div(1000)).utc.strftime("%Y-%m")
33
71
  end
34
72
 
73
+ # The release and SHA-1 on DB-IP's download page for the MMDB file of one kind: the last SHA1SUM before
74
+ # the link to that file, and after the link to any other. Nil when the page does not read that way.
75
+ def self.published_checksum(page, mode)
76
+ page = Js.scrub(page)
77
+ link = page.match(/download\.db-ip\.com\/free\/dbip-#{Regexp.escape(mode)}-lite-(\d{4}-\d{2})\.mmdb\.gz/)
78
+ return nil if link.nil?
79
+
80
+ before = link.pre_match
81
+ other = before.rindex("download.db-ip.com/free/dbip-")
82
+ card = other.nil? ? before : before[other..]
83
+ sha1 = card.scan(/SHA1SUM.{0,200}?\b([0-9a-f]{40})\b/im).last&.first
84
+ sha1.nil? ? nil : { "release" => link[1], "sha1" => sha1.downcase }
85
+ end
86
+
87
+ # Raises unless `bytes` is a DB-IP database of the kind asked for that a lookup can be made in: of a
88
+ # believable size, its search tree inside the file, built lately and not before the one in use (`in_use`,
89
+ # a time in milliseconds, or 0 for none), and answering for addresses everyone knows.
90
+ def self.check_database(bytes, mode, now, in_use = 0)
91
+ bytes = bytes.b
92
+ raise RuntimeError, "it unpacks to #{bytes.bytesize} bytes, too few for a location database" if bytes.bytesize < FEWEST_BYTES
93
+
94
+ marker = bytes.rindex(MARKER)
95
+ raise RuntimeError, "it is not an MMDB file" if marker.nil?
96
+
97
+ reader = begin
98
+ Mmdb.new(bytes)
99
+ rescue StandardError => e
100
+ raise RuntimeError, "it does not open as an MMDB file: #{e.message}"
101
+ end
102
+ meta = reader.metadata
103
+ major = meta["binary_format_major_version"]
104
+ raise RuntimeError, "its format is version #{major}, not 2" unless major == 2
105
+
106
+ type = meta["database_type"].to_s
107
+ raise RuntimeError, "it is a \"#{type}\" database, not DB-IP's #{mode} one" unless type.downcase == "dbip-#{mode}-lite"
108
+ raise RuntimeError, "it covers IP version #{meta["ip_version"]}, not 6" unless meta["ip_version"] == 6
109
+
110
+ size = meta["record_size"]
111
+ raise RuntimeError, "its records are #{size} bits" unless [24, 28, 32].include?(size)
112
+
113
+ nodes = meta["node_count"]
114
+ raise RuntimeError, "its search tree does not fit in the file" unless nodes.is_a?(Integer) && nodes.positive? && (nodes * size / 4.0) + 16 <= marker
115
+
116
+ epoch = meta["build_epoch"]
117
+ built = epoch.is_a?(Integer) ? epoch * 1000 : nil
118
+ if built.nil? || built > now + (2 * DAY) || built < now - OLDEST_BUILD
119
+ raise RuntimeError, "it was built on #{built.nil? ? "no date" : Time.at(epoch).utc.strftime("%Y-%m-%d")}"
120
+ end
121
+ raise RuntimeError, "it is older than the database in use" if built < in_use
122
+
123
+ KNOWN.each do |ip|
124
+ found = begin
125
+ reader.get(ip)
126
+ rescue StandardError
127
+ nil
128
+ end
129
+ country = found.is_a?(Hash) && found["country"].is_a?(Hash) ? found["country"]["iso_code"] : nil
130
+ raise RuntimeError, "it has no country for #{ip}" unless country.is_a?(String) && country.match?(/\A[A-Z]{2}\z/)
131
+ end
132
+ nil
133
+ end
134
+
35
135
  # The newest release on disk, or nil before the first download.
36
136
  def newest
37
137
  Dir.glob("#{@dir}/dbip-#{@mode}-lite-*.mmdb").max
@@ -81,84 +181,226 @@ module Runlight
81
181
 
82
182
  # Fetches this month's release when it is missing. A new month's file appears a day or so after the month
83
183
  # starts, so until then last month's is fetched when that is missing too. Older releases go once a new
84
- # one is ready. Safe to call often: once this month's file is there it reads only the folder.
184
+ # one is ready. Safe to call often: once this month's file is there it reads only the folder, and while
185
+ # the month's file is not published yet, or a download keeps failing, each try waits twice as long as the
186
+ # last, from five minutes up to six hours, so neither DB-IP nor the disk is asked for the whole file every
187
+ # few minutes. The wait is kept in a small file beside the releases, since `runlight cron` is a new
188
+ # process each time.
85
189
  def refresh(now)
86
190
  current = self.class.month(now)
87
191
  return if File.file?(file(current))
88
192
 
193
+ wait, retry_at = waiting
194
+ return if now < retry_at
195
+
89
196
  begin
90
197
  FileUtils.mkdir_p(@dir, mode: 0o755)
91
198
  rescue SystemCallError
92
199
  @log.call("Runlight: could not make the folder for location data, #{@dir}")
93
200
  return
94
201
  end
202
+ begin
203
+ fetch(current, now)
204
+ ensure
205
+ if File.file?(file(current))
206
+ FileUtils.rm_f(wait_file)
207
+ else
208
+ wait = [wait.zero? ? FIRST_WAIT : wait * 2, LONGEST_WAIT].min
209
+ begin
210
+ File.write(wait_file, "#{wait} #{now + wait}\n")
211
+ rescue SystemCallError
212
+ nil
213
+ end
214
+ end
215
+ end
216
+ end
217
+
218
+ private
219
+
220
+ # Where the wait after a failed try is kept: how long it was, and when the next try may start.
221
+ def wait_file
222
+ "#{@dir}/dbip-#{@mode}-retry"
223
+ end
224
+
225
+ # The wait kept from the last failed try, as [how long, when the next may start]; zeros when there is none.
226
+ def waiting
227
+ wait, retry_at = File.read(wait_file).split.map { |n| Integer(n, 10) }
228
+ wait.nil? || retry_at.nil? || wait.negative? ? [0, 0] : [wait, retry_at]
229
+ rescue SystemCallError, ArgumentError
230
+ [0, 0]
231
+ end
232
+
233
+ def file(release)
234
+ "#{@dir}/dbip-#{@mode}-lite-#{release}.mmdb"
235
+ end
236
+
237
+ # One GET that goes nowhere but where it was sent, and yields the headers and the body of a plain 200.
238
+ # Anything else is Refused, with its status.
239
+ def request(url, timeout)
240
+ @get.call(url, timeout) do |status, headers, body|
241
+ raise Refused, status unless status == 200
242
+
243
+ yield headers || {}, body || []
244
+ end
245
+ end
246
+
247
+ # The release DB-IP's download page offers for this kind of database, and the SHA-1 it gives for the
248
+ # unpacked file. Raises with why when there is none to read.
249
+ def published
250
+ url = "https://db-ip.com/db/download/ip-to-#{@mode}-lite"
251
+ page = begin
252
+ request(url, 30) do |_headers, body|
253
+ text = +"".b
254
+ body.each do |chunk|
255
+ text << chunk.to_s.b
256
+ raise RuntimeError, "it is more than #{MOST_PAGE_BYTES / 1024} KB" if text.bytesize > MOST_PAGE_BYTES
257
+ end
258
+ text
259
+ end
260
+ rescue StandardError => e
261
+ raise RuntimeError, "could not read DB-IP's checksums at #{url}: #{e.message}"
262
+ end
263
+ found = self.class.published_checksum(page, @mode)
264
+ raise RuntimeError, "found no checksum for the #{@mode} database at #{url}" if found.nil?
265
+
266
+ found
267
+ end
268
+
269
+ def fetch(release, now)
270
+ # A new month's file appears a day or so after the month starts; until then, last month's is current.
95
271
  at = Time.at(now.div(1000)).utc
96
272
  year = at.month == 1 ? at.year - 1 : at.year
97
- previous = format("%<year>04d-%<month>02d", year: year, month: at.month == 1 ? 12 : at.month - 1)
98
- [current, previous].each do |release|
99
- return if File.file?(file(release))
273
+ tries = [release, format("%<year>04d-%<month>02d", year: year, month: at.month == 1 ? 12 : at.month - 1)]
274
+ # The page says which release there is and what it must hash to, so only that file is asked for. When the
275
+ # page cannot be read, the newest release there is goes unchecked against it, and the log says so.
276
+ found = nil
277
+ unchecked = ""
278
+ begin
279
+ found = published
280
+ rescue StandardError => e
281
+ unchecked = e.message
282
+ end
283
+ if !found.nil? && !tries.include?(found["release"])
284
+ @log.call("Runlight: location data was not updated: DB-IP offers the #{found["release"]} release, which is neither this month's nor last month's")
285
+ return
286
+ end
287
+ (found.nil? ? tries : [found["release"]]).each do |name|
288
+ return if File.file?(file(name))
100
289
 
101
- url = "https://download.db-ip.com/free/dbip-#{@mode}-lite-#{release}.mmdb.gz"
102
- gz = "#{file(release)}.gz.partial"
103
- partial = "#{file(release)}.partial"
290
+ url = "https://download.db-ip.com/free/dbip-#{@mode}-lite-#{name}.mmdb.gz"
291
+ partial = "#{file(name)}.partial.#{Process.pid}"
104
292
  begin
105
- next unless @download.call(url, gz)
106
-
107
- self.class.gunzip(gz, partial)
108
- # A file that does not open as a database is never kept.
109
- Mmdb.open(partial)
110
- File.rename(partial, file(release))
293
+ save(url, partial, found.nil? ? nil : found["sha1"], now)
294
+ File.rename(partial, file(name))
295
+ # Older releases go once the new one is in place.
111
296
  Dir.glob("#{@dir}/dbip-#{@mode}-lite-*").each do |old|
112
- File.unlink(old) if old != file(release)
297
+ File.unlink(old) if old != file(name)
113
298
  rescue SystemCallError
114
299
  nil
115
300
  end
116
- @log.call("Runlight: location data from DB-IP (#{release}) is ready.")
301
+ if found.nil?
302
+ @log.call("Runlight: warning: location data from DB-IP (#{name}) could not be checked against DB-IP's published checksum (#{unchecked}). " \
303
+ "It was accepted as a DB-IP database of the right kind, without that check.")
304
+ end
305
+ @log.call("Runlight: location data from DB-IP (#{name}) is ready.")
117
306
  return
118
307
  rescue StandardError => e
119
- @log.call("Runlight: could not download location data from #{url}: #{e.message}")
120
- ensure
121
- FileUtils.rm_f(gz)
122
308
  FileUtils.rm_f(partial)
309
+ # Without the page to say which release there is, this month's not being out yet is no failure.
310
+ next if found.nil? && e.is_a?(Refused) && e.status == 404
311
+
312
+ # Whatever went wrong, the database in use stays in use.
313
+ @log.call("Runlight: location data was not updated from #{url}: #{e.message}")
123
314
  end
124
315
  end
316
+ @log.call("Runlight: location data was not updated: #{unchecked}, and no release could be downloaded without them") if found.nil?
125
317
  end
126
318
 
127
- def self.gunzip(from, to)
128
- Zlib::GzipReader.open(from) do |input|
129
- File.open(to, "wb") { |output| IO.copy_stream(input, output) }
319
+ # Downloads one release to `partial`, unpacked, and raises unless it is fit to use: the published SHA-1's
320
+ # (when there is one to hold it to), and a DB-IP database of this kind no older than the one in use.
321
+ def save(url, partial, sha1, now)
322
+ hash = OpenSSL::Digest.new("SHA1")
323
+ request(url, 10 * 60) do |headers, body|
324
+ raise RuntimeError, "the download is more than #{MOST_PACKED_BYTES / 1024 / 1024} MB" if Js.number(headers["content-length"] || 0) > MOST_PACKED_BYTES
325
+
326
+ unpack(body, partial, hash)
130
327
  end
131
- rescue Zlib::Error
132
- raise RuntimeError, "could not unpack #{from}"
328
+ got = hash.hexdigest
329
+ raise RuntimeError, "its SHA-1 is #{got}, and DB-IP publishes #{sha1}" if !sha1.nil? && got != sha1
330
+
331
+ self.class.check_database(File.binread(partial), @mode, now, in_use)
133
332
  end
134
333
 
135
- private
334
+ # Unpacks a gzipped body into a file as it arrives, hashing what is written. The stream must be whole and
335
+ # nothing may follow it: Zlib stops reading at the end of the stream, so what it left unread is looked for.
336
+ def unpack(body, partial, hash)
337
+ inflate = Zlib::Inflate.new(Zlib::MAX_WBITS + 16)
338
+ packed = 0
339
+ unpacked = 0
340
+ begin
341
+ File.open(partial, File::WRONLY | File::CREAT | File::TRUNC, 0o644) do |out|
342
+ body.each do |chunk|
343
+ chunk = chunk.to_s.b
344
+ next if chunk.empty?
136
345
 
137
- def file(release)
138
- "#{@dir}/dbip-#{@mode}-lite-#{release}.mmdb"
346
+ packed += chunk.bytesize
347
+ raise RuntimeError, "the location data is more than #{MOST_PACKED_BYTES / 1024 / 1024} MB" if packed > MOST_PACKED_BYTES
348
+ raise RuntimeError, "there is data after the end of its gzip stream" if inflate.finished?
349
+
350
+ inflate.inflate(chunk) do |piece|
351
+ unpacked += piece.bytesize
352
+ raise RuntimeError, "the location data is more than #{MOST_BYTES / 1024 / 1024} MB" if unpacked > MOST_BYTES
353
+
354
+ hash << piece
355
+ out.write(piece)
356
+ end
357
+ raise RuntimeError, "there is data after the end of its gzip stream" if inflate.finished? && inflate.total_in < packed
358
+ end
359
+ raise RuntimeError, "unexpected end of the gzip stream" unless inflate.finished?
360
+ end
361
+ rescue Zlib::Error => e
362
+ raise RuntimeError, "it is not gzip: #{e.message}"
363
+ ensure
364
+ inflate.close
365
+ end
139
366
  end
140
367
 
141
- # Downloads a file straight to disk, since a city database is too big to hold in memory. This is the one
142
- # download that does not go through a fetcher, which keeps whole answers in memory. Redirects are followed
143
- # on https only.
144
- def fetch_to(url, file, redirects = 5)
368
+ # When the newest release on disk was built, in milliseconds, or 0 with none (or one that does not open).
369
+ def in_use
370
+ file = newest
371
+ return 0 if file.nil?
372
+
373
+ File.open(file, "rb") do |handle|
374
+ epoch = Mmdb.new("", handle).metadata["build_epoch"]
375
+ epoch.is_a?(Integer) ? epoch * 1000 : 0
376
+ end
377
+ rescue StandardError
378
+ 0
379
+ end
380
+
381
+ # One GET over https with Net::HTTP, no redirect followed, the body given a part at a time (a city database
382
+ # is too big to hold packed in memory as well as unpacked), and the whole of it within `timeout` seconds.
383
+ def http_get(url, timeout)
145
384
  uri = URI(url)
146
385
  raise RuntimeError, "not https: #{url}" unless uri.scheme == "https"
147
386
 
148
- Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 15, read_timeout: 600) do |http|
149
- http.request(Net::HTTP::Get.new(uri)) do |answer|
150
- if answer.is_a?(Net::HTTPRedirection) && redirects.positive? && answer["location"]
151
- return fetch_to(URI.join(url, answer["location"]).to_s, file, redirects - 1)
152
- end
153
- return false unless answer.code == "200"
387
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
388
+ Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: [timeout, 15].min, read_timeout: [timeout, 60].min) do |http|
389
+ # Asked for as it is, so the length the server declares is the length of what arrives.
390
+ get = Net::HTTP::Get.new(uri, { "accept-encoding" => "identity", "user-agent" => "Runlight (+https://runlight.sh)" })
391
+ http.request(get) do |answer|
392
+ headers = {}
393
+ answer.each_header { |name, value| headers[name.downcase] = value }
394
+ parts = Enumerator.new do |out|
395
+ answer.read_body do |chunk|
396
+ raise RuntimeError, "it took more than #{timeout} seconds" if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
154
397
 
155
- File.open(file, "wb") do |out|
156
- answer.read_body { |chunk| out.write(chunk) }
398
+ out << chunk
399
+ end
157
400
  end
158
- return true
401
+ return yield(answer.code.to_i, headers, parts)
159
402
  end
160
403
  end
161
- false
162
404
  end
163
405
  end
164
406
  end
@@ -31,8 +31,19 @@ module Runlight
31
31
  EVERY = 5 * 60
32
32
 
33
33
  TOO_LARGE = Json.encode({ "error" => "That request is too large" })
34
+ # Shorter than this, a secret or token set by hand is short enough to guess.
35
+ SHORTEST = 32
34
36
  private_constant :TOO_LARGE
35
37
 
38
+ # What to say at start about a secret or token someone set by hand that is short enough to guess, or nil.
39
+ # The server still starts, since refusing would stop an install that ran before this was checked.
40
+ def self.short_warning(name, value)
41
+ return nil if value.nil? || Js.length(value) >= SHORTEST
42
+
43
+ does = name == "RUNLIGHT_SECRET" ? "It signs every session and encrypts the saved mail and assistant keys" : "Anyone who guesses it has the whole API, as the owner"
44
+ "Runlight: WARNING: #{name} is only #{Js.length(value)} characters long. #{does}. Set it to #{SHORTEST} or more random characters, such as the output of: openssl rand -hex 32"
45
+ end
46
+
36
47
  attr_reader :runlight, :accounts, :web, :routes
37
48
 
38
49
  # The standalone server from the environment and config.rb in root (the working folder by default), as a Rack
@@ -53,7 +64,10 @@ module Runlight
53
64
  # account is made with it instead.
54
65
  # - url: the dashboard's public address, such as https://stats.example.com. It can never become a link
55
66
  # domain, short links never answer on it, and emails link to it whatever Host header a request carries.
56
- # - trustProxy, geo, geoCredit, now, fetcher: as the Core's and the routes' options of those names.
67
+ # - trustProxy: whether X-Forwarded-For and friends count, for the visitor's address and the name a request
68
+ # came in on. Left unset they count only from a proxy on this computer or a private network; true believes
69
+ # them from anywhere, false never, and a header's name reads that one alone.
70
+ # - geo, geoCredit, now, fetcher: as the Core's and the routes' options of those names.
57
71
  # - setupCode: the one-time code that unlocks /setup while no account exists; setupWhere (true) says it is
58
72
  # written in setup.txt, for the page that asks for it.
59
73
  # - cronSecret: a bearer secret for POST /api/check, for a scheduler that calls it over HTTP.
@@ -71,6 +85,14 @@ module Runlight
71
85
  @public_host = @public_url.nil? ? nil : Routes.host_name(@public_url.host)
72
86
  @own_hosts = nil
73
87
  @schedule = nil
88
+ # Where each request came from, as the handler was told, for the routes' callbacks, which get the request alone.
89
+ @contexts = WeakKeys.new
90
+ # A token short enough to guess gets ten wrong tries per address in fifteen minutes, after which that
91
+ # address's tries are all refused until the time is up. A long one cannot be guessed, so nothing is counted
92
+ # for it and nobody's wrong tries can keep a script that shares their address out. Counted in this
93
+ # process alone, as every count keyed by an address is.
94
+ @guessable = !@token.nil? && Js.length(@token) < SHORTEST
95
+ @guesses = Accounts::Throttle.new(@store, "token", 10, memory: true)
74
96
 
75
97
  core = {
76
98
  "store" => @store,
@@ -118,8 +140,16 @@ module Runlight
118
140
  "accounts" => @web,
119
141
  "authorize" => lambda do |request|
120
142
  auth = request.headers.get("authorization") || ""
121
- if !@token.nil? && auth.downcase.start_with?("bearer ") && Accounts::Crypto.same_text(Js.trim(auth[7..]), @token)
122
- next true
143
+ given = auth.downcase.start_with?("bearer ") ? Js.trim(auth[7..]) : ""
144
+ # A token made in Settings (rl_...) is the routes' to check, never a guess at this one.
145
+ if !@token.nil? && given != "" && (!given.start_with?("rl_") || @token.start_with?("rl_"))
146
+ from = rl.client_ip(request, @contexts[request] || {})
147
+ from = "unknown" if from == ""
148
+ unless @guessable && @guesses.blocked(from, @now.call)
149
+ next true if Accounts::Crypto.same_text(given, @token)
150
+
151
+ @guesses.record_failure(from, @now.call) if @guessable
152
+ end
123
153
  end
124
154
 
125
155
  access = @web.access(request)
@@ -130,11 +160,15 @@ module Runlight
130
160
  }
131
161
  routes["origin"] = @public_url.origin unless @public_url.nil?
132
162
  @routes = rl.routes(routes)
163
+ # A link at one of the server's own paths would open at /go/<slug> and never on a link domain, where the
164
+ # server's page answers first, so no new link takes one.
165
+ rl.links.reserved = SERVER_PATHS.map { |path| path[1..] }.freeze
133
166
  end
134
167
 
135
168
  # The answer to one request. context: { "ip" => the client's address }.
136
169
  def handle(request, context = {})
137
170
  path = Http::Url.new(request.url).pathname
171
+ @contexts[request] = context
138
172
  begin
139
173
  # A domain pointed at this server for short links answers at its root, with links one segment deep. The
140
174
  # server's own pages and its public address never answer as links, and "/" stays the dashboard for someone
@@ -243,9 +277,11 @@ module Runlight
243
277
  warn "Runlight: #{e.message}"
244
278
  end
245
279
 
246
- # The name a request came in on, read as link domains read it.
280
+ # The name a request came in on, read as link domains read it: a proxy's X-Forwarded-Host only where the
281
+ # library believes a proxy's headers at all, so a client that reaches the server straight from the internet
282
+ # cannot name the host itself.
247
283
  def host_of(request)
248
- forwarded = @trust_proxy == false ? nil : request.headers.get("x-forwarded-host")
284
+ forwarded = @runlight.forwarded_host(request, @contexts[request] || {})
249
285
  Routes.host_name(forwarded || request.headers.get("host") || Http::Url.new(request.url).host)
250
286
  end
251
287
 
@@ -26,7 +26,7 @@ module Runlight
26
26
  def maps
27
27
  return unless @by_host.nil?
28
28
 
29
- # Later entries win, as Map.set does: the alias "kit" names Newsletter, not Kit.
29
+ # Later entries win, as Map.set does.
30
30
  by_host = {}
31
31
  Data::Sources::SOURCES.each do |source|
32
32
  source["hosts"].each { |host| by_host[host] = source }
@@ -35,8 +35,9 @@ module Runlight
35
35
  @by_host = by_host
36
36
  end
37
37
 
38
+ # A query value as it is stored: tidied (a decoded %00 is no text), trimmed, and cut by character.
38
39
  def clip(value, max = 200)
39
- Js.slice(Js.trim(value || ""), 0, max)
40
+ Payload.clean_text(Js.trim(Payload.tidy(value || "")), max)
40
41
  end
41
42
 
42
43
  def strip_www(host)
@@ -77,6 +77,20 @@ module Runlight
77
77
  dialect == "sqlite" ? "rl_events e INDEXED BY rl_events_site_kind_ts" : "rl_events e"
78
78
  end
79
79
 
80
+ # Text Postgres will not read as jsonb: an escaped NUL, or half of a surrogate pair, each after an even
81
+ # number of backslashes. JSON.stringify writes both for a string that holds them, and they are valid JSON.
82
+ PG_UNREADABLE_PROPS = '(?<!\\\\)(\\\\\\\\)*(\\\\u0000|\\\\u[dD][89abAB][0-9a-fA-F]{2}(?!\\\\u[dD][c-fC-F][0-9a-fA-F]{2}))|(?<!\\\\)(?<!\\\\u[dD][89abAB][0-9a-fA-F]{2})(\\\\\\\\)*\\\\u[dD][c-fC-F][0-9a-fA-F]{2}'
83
+
84
+ # An event's props as the database can read them as JSON, or NULL for a row it cannot: Postgres refuses an
85
+ # escaped NUL or half a surrogate pair, and MySQL the half pair. Such a row counts as one with no props,
86
+ # rather than failing every report that reads its event. SQLite reads them as they are.
87
+ def readable_props(dialect)
88
+ return "(CASE WHEN e.props !~ '#{PG_UNREADABLE_PROPS}' THEN e.props END)::jsonb" if dialect == "postgres"
89
+ return "(CASE WHEN JSON_VALID(e.props) THEN e.props END)" if dialect == "mysql"
90
+
91
+ "e.props"
92
+ end
93
+
80
94
  # Runs a query over pieces of a list and joins the answers, in order.
81
95
  def in_pieces(items, size)
82
96
  out = []