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
@@ -13,8 +13,10 @@ module Runlight
13
13
  # Postgres. Each `?` outside quotes is filled in on the client with the
14
14
  # value written as a literal, as mysql2 fills them in for the TypeScript
15
15
  # driver. On MySQL each statement also goes through mysql_text first: a
16
- # "quoted" name in backticks, and a backslash inside 'text' doubled, since
17
- # MySQL reads it as an escape where standard SQL takes it literally.
16
+ # "quoted" name in backticks, and text written so that it reads the same
17
+ # whatever the session's SQL mode: a quote doubled, and anything holding a
18
+ # backslash as hex, since MySQL reads a backslash as an escape or as itself
19
+ # depending on NO_BACKSLASH_ESCAPES. Nothing about the session is changed.
18
20
  #
19
21
  # Rows come back as Hashes keyed by column name; numbers may arrive as
20
22
  # strings, so the store casts what it reads.
@@ -43,10 +45,6 @@ module Runlight
43
45
  # characters at most.
44
46
  MYSQL_LOCK = "CONCAT('runlight:', LEFT(SHA2(COALESCE(DATABASE(), ''), 256), 48))"
45
47
 
46
- # The session's sql_mode as it was, less NO_BACKSLASH_ESCAPES, wherever it sits in the list, as
47
- # stores/mysql.ts sets it.
48
- NO_BACKSLASH_ESCAPES_OFF = "SET SESSION sql_mode = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', @@SESSION.sql_mode, ','), ',NO_BACKSLASH_ESCAPES,', ','))"
49
-
50
48
  # Deleted rows, such as a day's salt once it is gone, are overwritten where that costs no extra writes, so
51
49
  # they do not linger in the file's free space. Rails' pragmas setting takes this one only as on or off.
52
50
  SECURE_DELETE = "PRAGMA secure_delete = FAST"
@@ -68,8 +66,8 @@ module Runlight
68
66
  @held = 0
69
67
  # Set on the thread inside a SQLite turn, whose BEGIN IMMEDIATE Rails does not know about.
70
68
  @turn_key = :"runlight_turn_#{object_id}"
71
- # The MySQL sessions, and the SQLite connections this database opened, already set up, by their driver
72
- # connection, which a reconnect replaces.
69
+ # The SQLite connections this database opened, already set up, by their driver connection, which a
70
+ # reconnect replaces.
73
71
  @set_up = ObjectSpace::WeakMap.new
74
72
  end
75
73
 
@@ -190,13 +188,13 @@ module Runlight
190
188
  end
191
189
 
192
190
  # SQL written for SQLite and Postgres as MySQL and MariaDB read it: a "quoted" identifier is quoted with
193
- # backticks, and a backslash inside 'text' is doubled. With params, each `?` outside quotes becomes its
194
- # value through the block (mysql2's escaping when none is given).
191
+ # backticks, and 'text' is written as mysql_string writes it. With params, each `?` outside quotes becomes
192
+ # its value through the block (mysql_escape when none is given).
195
193
  def self.mysql_text(sql, params = nil, &escape)
196
194
  fill(sql, params, mysql: true, &(escape || method(:mysql_escape)))
197
195
  end
198
196
 
199
- # A value as a MySQL literal, as mysql2's escape() writes the values Runlight binds.
197
+ # A value as a MySQL literal that reads the same in every SQL mode.
200
198
  def self.mysql_escape(value)
201
199
  case value
202
200
  when nil then "NULL"
@@ -204,17 +202,23 @@ module Runlight
204
202
  when false then "false"
205
203
  when Integer then value.to_s
206
204
  when Float then Json.number(value)
207
- else
208
- escaped = value.to_s.gsub(/[\0\b\t\x1a\n\r"'\\]/) do |c|
209
- { "\0" => "\\0", "\b" => "\\b", "\t" => "\\t", "\x1a" => "\\Z", "\n" => "\\n", "\r" => "\\r",
210
- '"' => '\\"', "'" => "\\'", "\\" => "\\\\" }[c]
211
- end
212
- "'#{escaped}'"
205
+ else mysql_string(Js.scrub(value.to_s))
213
206
  end
214
207
  end
215
208
 
209
+ # Text as a MySQL literal. Whether a backslash inside quotes is an escape or itself depends on the
210
+ # session's NO_BACKSLASH_ESCAPES mode, which a reconnect inside a statement can change under it, so no
211
+ # backslash is ever written inside quotes: a quote is doubled, which every mode reads as one quote, and
212
+ # text holding a backslash (or a NUL or Ctrl-Z, which some clients and logs cut at) is written as hex,
213
+ # read as utf8mb4. Nothing a value holds can then end it early, whatever the session is set to.
214
+ def self.mysql_string(text)
215
+ return "_utf8mb4 X'#{text.unpack1("H*")}'" if text.match?(/[\\\0\x1a]/)
216
+
217
+ "'#{text.gsub("'", "''")}'"
218
+ end
219
+
216
220
  # Walks the statement once: each `?` outside quotes becomes the next value through the block, and on
217
- # MySQL a "quoted" name takes backticks and a backslash in 'text' is doubled.
221
+ # MySQL a "quoted" name takes backticks and 'text' is written again as mysql_string writes it.
218
222
  def self.fill(sql, params, mysql: false)
219
223
  return sql if params.nil? && !mysql
220
224
  return sql if !mysql && params.empty? && !sql.include?("?")
@@ -222,18 +226,34 @@ module Runlight
222
226
  out = +""
223
227
  n = 0
224
228
  quote = nil
225
- sql.each_char do |ch|
226
- if quote
229
+ # On MySQL, the 'text' being read, written whole once it ends.
230
+ held = nil
231
+ chars = sql.chars
232
+ at = -1
233
+ while (at += 1) < chars.length
234
+ ch = chars[at]
235
+ if held
236
+ if ch != "'"
237
+ held << ch
238
+ elsif chars[at + 1] == "'"
239
+ # A doubled quote is one quote inside the text.
240
+ held << "'"
241
+ at += 1
242
+ else
243
+ out << mysql_string(held)
244
+ held = nil
245
+ end
246
+ elsif quote
227
247
  if ch == quote
228
248
  quote = nil
229
249
  out << (mysql && ch == '"' ? "`" : ch)
230
- elsif mysql && quote == "'" && ch == "\\"
231
- out << "\\\\"
232
250
  elsif mysql && quote == '"' && ch == "`"
233
251
  out << "``"
234
252
  else
235
253
  out << ch
236
254
  end
255
+ elsif mysql && ch == "'"
256
+ held = +""
237
257
  elsif ch == "'" || ch == '"' || ch == "`"
238
258
  quote = ch
239
259
  out << (mysql && ch == '"' ? "`" : ch)
@@ -246,6 +266,8 @@ module Runlight
246
266
  out << ch
247
267
  end
248
268
  end
269
+ # Text left open is written as it came, for the database to refuse.
270
+ out << "'" << held unless held.nil?
249
271
  raise ArgumentError, "Runlight: a statement has more values than placeholders" if !params.nil? && n != params.length
250
272
 
251
273
  out
@@ -255,29 +277,28 @@ module Runlight
255
277
 
256
278
  def connection
257
279
  @connection_class.connection_pool.with_connection do |c|
258
- set_up(c) if dialect == "mysql" || (@owned && dialect == "sqlite")
280
+ set_up(c) if @owned && dialect == "sqlite"
259
281
  yield c
260
282
  end
261
283
  end
262
284
 
263
- # Values are escaped with backslashes, which a server set to NO_BACKSLASH_ESCAPES reads as text, so a
264
- # quote could end the value early. Every MySQL session Runlight uses drops that one mode first, an app's
265
- # own ActiveRecord connection's too, and again after a reconnect, which starts the session over. A SQLite
266
- # file Runlight opened itself turns on secure_delete, as stores/sqlite.ts does.
285
+ # A SQLite file Runlight opened itself turns on secure_delete, as stores/sqlite.ts does. A MySQL session
286
+ # needs nothing set: values are written to read the same in every SQL mode (mysql_string).
267
287
  def set_up(c)
268
288
  raw = c.instance_variable_get(:@raw_connection)
269
289
  return if raw && @set_up[raw]
270
290
 
271
- c.execute(dialect == "sqlite" ? SECURE_DELETE : NO_BACKSLASH_ESCAPES_OFF, "Runlight")
291
+ c.execute(SECURE_DELETE, "Runlight")
272
292
  raw = c.instance_variable_get(:@raw_connection)
273
- wait_without_the_lock(raw) if dialect == "sqlite"
293
+ wait_without_the_lock(raw)
274
294
  @set_up[raw] = true if raw
275
295
  end
276
296
 
277
- # Rails 7.2 sets SQLite's busy timeout with busy_timeout, which sleeps in C holding Ruby's global lock. A
297
+ # SQLite's busy_timeout, as sqlite3 1.x sets it, sleeps in C holding Ruby's global lock. A
278
298
  # thread waiting for the file's write lock then stops the thread of the same process that holds it from
279
299
  # ever finishing, so the wait runs out and raises "database is locked". busy_handler_timeout= (sqlite3
280
- # 2.x, and what Rails 8 uses) waits the same time but lets other threads run.
300
+ # 2.x, which Rails 8 needs) waits the same time but lets other threads run. Kept for an app that sets up
301
+ # its own connection the old way.
281
302
  def wait_without_the_lock(raw)
282
303
  return unless raw.respond_to?(:busy_handler_timeout=)
283
304
 
@@ -295,7 +316,6 @@ module Runlight
295
316
  warn "Runlight: a #{dialect == "mysql" ? "MySQL" : "Postgres"} connection was lost; it reconnects on the next query. #{e.message}"
296
317
  connection do |c|
297
318
  c.reconnect!
298
- set_up(c) if dialect == "mysql"
299
319
  block.call(c)
300
320
  end
301
321
  end
data/lib/runlight/geo.rb CHANGED
@@ -30,11 +30,11 @@ module Runlight
30
30
  country = "" if !country.match?(/\A[A-Z]{2}\z/) || country == "XX" || country == "T1"
31
31
  # A code ("CA", "US-CA") is kept as ISO 3166-2; a name from a database
32
32
  # that has no codes ("California") is kept readable, as "US-California".
33
- raw = Js.trim(text(location["region"]))
33
+ raw = Js.trim(Payload.tidy(text(location["region"])))
34
34
  region = raw.match?(/\A([A-Za-z]{2}-)?[A-Za-z0-9]{1,3}\z/) ? raw.upcase : Js.slice(raw, 0, 80)
35
35
  region = "#{country}-#{region}" if region != "" && !region.match?(/\A[A-Z]{2}-/) && country != ""
36
36
  region = "" if country == ""
37
- city = country == "" ? "" : Js.slice(text(location["city"]), 0, 100)
37
+ city = country == "" ? "" : Js.slice(Payload.tidy(text(location["city"])), 0, 100)
38
38
  { "country" => country, "region" => region, "city" => city }
39
39
  end
40
40
 
@@ -53,16 +53,35 @@ module Runlight
53
53
  @body.call(Writer.new(block))
54
54
  end
55
55
 
56
- # [status, headers, body] for Rack. Header names are lowercase, as Rack 3 asks; Set-Cookie values are
57
- # one per line.
56
+ # [status, headers, body] for Rack. Header names are lowercase, as Rack 3 asks. Several Set-Cookie values
57
+ # are an Array under Rack 3, which takes no line break in a value, and one per line under Rack 2 (or
58
+ # with no rack gem loaded, where servers split on the line break), which takes no Array.
58
59
  def to_rack
59
60
  headers = {}
60
61
  @headers.all.each do |name, values|
61
- headers[name] = name == "set-cookie" ? values.join("\n") : values.join(", ")
62
+ headers[name] = if name != "set-cookie" then values.join(", ")
63
+ elsif values.length > 1 && Response.rack3? then values.dup
64
+ else values.join("\n")
65
+ end
62
66
  end
63
67
  [@status, headers, RackBody.new(self)]
64
68
  end
65
69
 
70
+ # Whether the rack gem loaded is 3 or later. Its version is in a file of its own, which an app that
71
+ # loaded only parts of rack may not have read yet.
72
+ def self.rack3?
73
+ return false unless defined?(::Rack)
74
+
75
+ unless ::Rack.respond_to?(:release)
76
+ begin
77
+ require "rack/version"
78
+ rescue LoadError
79
+ return false
80
+ end
81
+ end
82
+ ::Rack.respond_to?(:release) && ::Rack.release.to_i >= 3
83
+ end
84
+
66
85
  # What a streamed body writes to: each part goes straight to the block.
67
86
  class Writer
68
87
  def initialize(block)
data/lib/runlight/icon.rb CHANGED
@@ -20,7 +20,8 @@ module Runlight
20
20
  # A few hundred sites at most; past that the oldest go, so the cache cannot grow without end.
21
21
  CACHE_SIZE = 500
22
22
  # A <link> tag, matched on bytes so case folding stays ASCII, as JavaScript's /i does.
23
- LINK = /<link(?![A-Za-z0-9_])[^>]*>/in
23
+ # A tag is at most a few thousand characters; the bound keeps a page of unclosed tags from being read over and over.
24
+ LINK = /<link(?![A-Za-z0-9_])[^<>]{0,4000}>/in
24
25
  # Where the system has it, opening a link fails rather than following it.
25
26
  NOFOLLOW = File.const_defined?(:NOFOLLOW) ? File::NOFOLLOW : 0
26
27
  private_constant :TIMEOUT_MS, :MAX_BYTES, :DAY, :CACHE_SIZE, :LINK, :NOFOLLOW
@@ -13,6 +13,10 @@ module Runlight
13
13
  # At most this many rows in one request.
14
14
  CSV_BATCH = 2000
15
15
 
16
+ # The earliest time a row may have: the start of 2000. A bare number is read as a Unix time, so a date written
17
+ # 20240501 would otherwise land in 1970, and the site's history would begin there.
18
+ CSV_EARLIEST = 946_684_800_000
19
+
16
20
  SCHEME = %r{\A[a-z][a-z0-9+.-]*://}i
17
21
  private_constant :SCHEME
18
22
 
@@ -26,9 +30,15 @@ module Runlight
26
30
  nil
27
31
  end
28
32
 
29
- # A row's time in milliseconds, or NaN. ISO 8601 with or without a zone, "2024-05-01 12:34:56"
30
- # (both read as UTC when no zone is given, as Umami writes them), or a Unix time in seconds or milliseconds.
33
+ # A row's time in milliseconds, or NaN, as it also is for a time before CSV_EARLIEST. ISO 8601 with or
34
+ # without a zone, "2024-05-01 12:34:56" (both read as UTC when no zone is given, as Umami writes them),
35
+ # or a Unix time in seconds or milliseconds.
31
36
  def row_time(row, format)
37
+ ts = read_time(row, format)
38
+ ts >= CSV_EARLIEST ? ts : Float::NAN
39
+ end
40
+
41
+ def read_time(row, format)
32
42
  text = Js.trim((format == "umami" ? row["created_at"] : row["time"]) || "")
33
43
  return Float::NAN if text.empty?
34
44
 
@@ -151,7 +161,7 @@ module Runlight
151
161
  }
152
162
  end
153
163
 
154
- private_class_method :cell, :own_key, :full_referrer
164
+ private_class_method :cell, :own_key, :full_referrer, :read_time
155
165
  end
156
166
  end
157
167
  end
@@ -78,7 +78,8 @@ module Runlight
78
78
  "os" => Client.field(click, "os"),
79
79
  })
80
80
  end
81
- break if events.length < 1000
81
+ # No more than a link keeps: the oldest clicks come first, and a longer history ends here.
82
+ break if events.length < 1000 || clicks.length >= Write::MAX_LINK_CLICKS
82
83
 
83
84
  page += 1
84
85
  end
@@ -30,7 +30,8 @@ module Runlight
30
30
  client = Client.new(runlight.fetcher)
31
31
  importer = Importers.const_get(name).new(client, -> { runlight.now })
32
32
  known = lambda do |source_id, slug = nil, url = nil|
33
- return true unless runlight.store.link_by_id(Write.imported_link_id(source, Js.string(source_id))).nil?
33
+ # A link imported before and deleted since counts too, so its history is not fetched to be thrown away.
34
+ return true if runlight.store.link_exists(Write.imported_link_id(source, Js.string(source_id)))
34
35
  return false if !Js.truthy?(slug) || !Js.truthy?(url)
35
36
 
36
37
  taken = runlight.store.link_by_slug(Js.string(slug))
@@ -64,6 +64,9 @@ module Runlight
64
64
  loop do
65
65
  body = @http.get_json("#{base}/api#{path}&page=#{page}&pageSize=1000", { "headers" => headers })
66
66
  out.concat(body["data"])
67
+ # No more than a link keeps: a longer history, or a server that never stops, ends here.
68
+ return out.first(Write::MAX_LINK_CLICKS) if out.length >= Write::MAX_LINK_CLICKS
69
+
67
70
  return out if out.length >= (body["count"].nil? ? Float::INFINITY : body["count"]) || body["data"] == []
68
71
 
69
72
  page += 1
@@ -261,6 +261,14 @@ module Runlight
261
261
  }
262
262
  end
263
263
 
264
+ # Whether a hostname can be the host of an address, and nothing more than a host.
265
+ def valid_host?(host)
266
+ return false if host == "" || host.match?(%r{[/?#@\\]})
267
+
268
+ url = Http::Url.parse("https://#{host}/")
269
+ !url.nil? && url.hostname != ""
270
+ end
271
+
264
272
  # Writes one imported pageview or event as part of a Runlight visit. Visitors
265
273
  # are hashed per day from the hit's key, as live visitors are hashed per day,
266
274
  # and a hit within thirty minutes of the visitor's last one joins that visit.
@@ -273,6 +281,9 @@ module Runlight
273
281
  # A visit that runs past midnight keeps the id it started with, as a live one does.
274
282
  yesterday = Write.hex_id("#{ns}:#{e["key"]}:#{Dates.add_days(day, -1)}", 16)
275
283
  host = Js.lower(e["hostname"].empty? ? site["hostnames"][0] || "imported.invalid" : e["hostname"])
284
+ # A hostname no address can hold (a space in it, say) is the site's own instead, so one bad cell is one
285
+ # row under the site's name rather than a failed batch.
286
+ host = valid_host?(site["hostnames"][0] || "") ? Js.lower(site["hostnames"][0]) : "imported.invalid" unless valid_host?(host)
276
287
  url = Http::Url.parse("https://#{host}#{e["path"].empty? ? "/" : e["path"]}#{e["query"].empty? ? "" : "?#{e["query"].sub(/\A\?/, "")}"}") ||
277
288
  Http::Url.new("https://#{host}/")
278
289
  page = Sources.parse_page(url)
@@ -282,7 +293,7 @@ module Runlight
282
293
  id = Write.hex_id("#{ns}:#{e["key"]}:#{e["ts"]}")
283
294
  store.db.run("DELETE FROM rl_sessions WHERE id = ?", [id])
284
295
  country = Js.slice(Js.upper(e["country"]), 0, 2)
285
- raw_region = e["region"]
296
+ raw_region = Write.place_name(e["region"])
286
297
  region = raw_region.empty? ? "" : Js.slice(Js.upper(raw_region.include?("-") ? raw_region : "#{country}-#{raw_region}"), 0, 10)
287
298
  known = country.match?(/\A[A-Z]{2}\z/)
288
299
  store.insert_session(
@@ -300,14 +311,14 @@ module Runlight
300
311
  "utmContent" => page["utm"]["content"],
301
312
  "country" => known ? country : "",
302
313
  "region" => known ? region : "",
303
- "city" => Js.slice(e["city"], 0, 100),
314
+ "city" => Js.slice(Write.place_name(e["city"]), 0, 100),
304
315
  "browser" => Write.browser(e["browser"]),
305
316
  "browserVersion" => "",
306
317
  "os" => Write.system_name(e["os"]),
307
318
  "osVersion" => "",
308
319
  "device" => Write.device(e["device"]),
309
- "screen" => Js.slice(e["screen"], 0, 20),
310
- "language" => Js.slice(e["language"], 0, 35),
320
+ "screen" => Write.screen_size(e["screen"]),
321
+ "language" => Write.language_tag(e["language"]),
311
322
  ),
312
323
  )
313
324
  # No engaged time is known, so duration falls back to first-to-last pageview.
@@ -386,7 +397,7 @@ module Runlight
386
397
  counts.merge("skipped" => skipped, "secret" => key)
387
398
  end
388
399
 
389
- private_class_method :progress_key, :all, :write_step, :referrer_of, :from_umami, :write_event
400
+ private_class_method :progress_key, :all, :write_step, :referrer_of, :from_umami, :write_event, :valid_host?
390
401
  end
391
402
  end
392
403
  end
@@ -8,7 +8,16 @@ module Runlight
8
8
  SHORTENER_DOMAINS = %w[bit.ly bitly.com j.mp dub.sh dub.co dub.link short.gy rebrand.ly rebrandly.com rb.gy].freeze
9
9
  # The most clicks a day one imported link gets from a daily count.
10
10
  MAX_DAILY = 10_000
11
- private_constant :SHORTENER_DOMAINS, :MAX_DAILY
11
+ # The most clicks one imported link brings with it, each click or each one of a daily count. The rest of a
12
+ # longer history is left behind, so no source, however much it sends, can fill memory or hold the database.
13
+ MAX_LINK_CLICKS = 100_000
14
+ # An IPv4 address, or what reads as an IPv6 one, anywhere in a text.
15
+ ADDRESS = /(\A|[^\d.])\d{1,3}(\.\d{1,3}){3}(?![\d.])|[0-9a-f]{0,4}(:[0-9a-f]{0,4}){2,}/in
16
+ # What a user agent has and a place name does not: a product with its version (Chrome/129), or its usual first words.
17
+ AGENT = %r{[a-z]/\d|mozilla|applewebkit}in
18
+ # A browser or system as a name: a word or a few, not starting with a digit, without the punctuation of a user agent.
19
+ NAME = /\A[A-Za-z_][A-Za-z0-9 ._+-]{0,39}\z/
20
+ private_constant :SHORTENER_DOMAINS, :MAX_DAILY, :ADDRESS, :AGENT, :NAME
12
21
 
13
22
  # Browser and system names as other tools write them, in Runlight's spelling.
14
23
  BROWSERS = {
@@ -46,14 +55,39 @@ module Runlight
46
55
  v == "" ? "" : Js.upper(Js.slice(v, 0, 1)) + Js.slice(v, 1)
47
56
  end
48
57
 
49
- # A browser name in Runlight's spelling: a known one, or the name with a capital first letter.
58
+ # Runlight never stores an IP address or a full user agent, and a file or another tool can hold either in
59
+ # any column. A name that is not one Runlight knows is kept only when it reads as a name, and nothing else.
60
+ def named(name)
61
+ text = Js.trim(name)
62
+ text.match?(NAME) && !text.b.match?(ADDRESS) ? text : ""
63
+ end
64
+
65
+ # A browser name in Runlight's spelling: a known one, or a name with a capital first letter, or none for anything else.
50
66
  def browser(name)
51
- BROWSERS[Js.lower(name)] || title(name)
67
+ BROWSERS[Js.lower(name)] || title(named(name))
52
68
  end
53
69
 
54
- # A system name in Runlight's spelling, or the name as given.
70
+ # A system name in Runlight's spelling, or a name as given, or none for anything that is not a name.
55
71
  def system_name(name)
56
- SYSTEMS[Js.lower(name)] || name
72
+ SYSTEMS[Js.lower(name)] || named(name)
73
+ end
74
+
75
+ # Free text about a place as given, or none when it holds an address or reads as a user agent.
76
+ def place_name(name)
77
+ bytes = Js.scrub(name).b
78
+ bytes.match?(ADDRESS) || bytes.match?(AGENT) ? "" : name
79
+ end
80
+
81
+ # A screen as 1440x900, or none.
82
+ def screen_size(value)
83
+ text = Js.trim(value)
84
+ text.match?(/\A\d{1,5}x\d{1,5}\z/) ? text : ""
85
+ end
86
+
87
+ # A language tag such as en or pt-BR, or none.
88
+ def language_tag(value)
89
+ text = Js.trim(value)
90
+ text.match?(/\A[A-Za-z]{2,3}([-_][A-Za-z0-9]{1,8}){0,3}\z/) ? text : ""
57
91
  end
58
92
 
59
93
  def device(name)
@@ -84,7 +118,9 @@ module Runlight
84
118
  def write_link(runlight, site, source, foreign, history, link_domain = ->(_domain) {})
85
119
  source_id = Js.string(foreign["sourceId"])
86
120
  id = imported_link_id(source, source_id)
87
- return { "status" => "skipped", "clicks" => 0 } unless runlight.store.link_by_id(id).nil?
121
+ # Here already, or imported once and deleted since. A deleted link keeps its row and its clicks, so it is
122
+ # left as it is: writing it again would clear those clicks and the visits they opened, then fail on its id.
123
+ return { "status" => "skipped", "clicks" => 0 } if runlight.store.link_exists(id)
88
124
 
89
125
  slug = foreign["slug"].to_s
90
126
  taken = runlight.store.link_by_slug(slug)
@@ -125,6 +161,8 @@ module Runlight
125
161
 
126
162
  made = {}
127
163
  (history["clicks"] || []).each do |c|
164
+ break if clicks >= MAX_LINK_CLICKS
165
+
128
166
  ts = c["ts"]
129
167
  next unless ts.is_a?(Integer) || (ts.is_a?(Float) && ts.finite?)
130
168
 
@@ -143,7 +181,7 @@ module Runlight
143
181
  Http::Url.new("https://#{host}/#{slug}")
144
182
  page = Sources.parse_page(url)
145
183
  country = Js.slice(Js.upper(str(c, "country")), 0, 2)
146
- raw_region = str(c, "region")
184
+ raw_region = place_name(str(c, "region"))
147
185
  region = raw_region.empty? ? "" : Js.slice(Js.upper(raw_region.include?("-") ? raw_region : "#{country}-#{raw_region}"), 0, 10)
148
186
  store.insert_session(
149
187
  {
@@ -160,14 +198,14 @@ module Runlight
160
198
  "utmContent" => page["utm"]["content"],
161
199
  "country" => country.match?(/\A[A-Z]{2}\z/) ? country : "",
162
200
  "region" => country.empty? ? "" : region,
163
- "city" => Js.slice(str(c, "city"), 0, 100),
201
+ "city" => Js.slice(place_name(str(c, "city")), 0, 100),
164
202
  "browser" => browser(str(c, "browser")),
165
203
  "browserVersion" => "",
166
204
  "os" => system_name(str(c, "os")),
167
205
  "osVersion" => "",
168
206
  "device" => device(str(c, "device")),
169
- "screen" => text(c, "screen"),
170
- "language" => text(c, "language"),
207
+ "screen" => screen_size(text(c, "screen")),
208
+ "language" => language_tag(text(c, "language")),
171
209
  ),
172
210
  )
173
211
  store.db.run("UPDATE rl_sessions SET imported = 1 WHERE id = ?", [session])
@@ -188,7 +226,7 @@ module Runlight
188
226
  next if (start.is_a?(Float) && !start.finite?) || !(d["clicks"].is_a?(Numeric) && d["clicks"].positive?)
189
227
 
190
228
  # A day's count is capped, so one made-up figure from a source cannot write millions of rows.
191
- n = [d["clicks"], MAX_DAILY].min.floor
229
+ n = [d["clicks"].floor, MAX_DAILY, MAX_LINK_CLICKS - clicks].min
192
230
  i = 0
193
231
  while i < n
194
232
  store.insert_event({
@@ -218,7 +256,7 @@ module Runlight
218
256
  { "status" => "created", "clicks" => clicks }
219
257
  end
220
258
 
221
- private_class_method :str, :text
259
+ private_class_method :str, :text, :named
222
260
  end
223
261
  end
224
262
  end
@@ -12,8 +12,13 @@ module Runlight
12
12
  ALPHABET = "abcdefghijkmnpqrstuvwxyz23456789"
13
13
  private_constant :ALPHABET
14
14
 
15
+ # Slugs no new link may take, for a host whose own pages sit where a link domain's links do: the standalone
16
+ # server answers /login, /api, and the rest on every name, so a link there would never open on its own domain.
17
+ attr_accessor :reserved
18
+
15
19
  def initialize(runlight)
16
20
  @runlight = runlight
21
+ @reserved = [].freeze
17
22
  end
18
23
 
19
24
  # Six characters from an alphabet without look-alikes (no 0/o, 1/l).
@@ -147,12 +152,16 @@ module Runlight
147
152
 
148
153
  taken = @runlight.store.link_by_slug(wanted)
149
154
  raise LinkError.new("/#{wanted} is already taken", "link_taken", { "slug" => wanted }) if !taken.nil? && taken["id"] != except
155
+ # A link made before the slug was kept back keeps it.
156
+ if @reserved.include?(wanted) && taken.nil?
157
+ raise LinkError.new("/#{wanted} is one of this server's own pages, so a link there would never open on a link domain", "link_reserved", { "slug" => wanted })
158
+ end
150
159
 
151
160
  return wanted
152
161
  end
153
162
  8.times do
154
163
  slug = self.class.random_slug
155
- return slug if @runlight.store.link_by_slug(slug).nil?
164
+ return slug if !@reserved.include?(slug) && @runlight.store.link_by_slug(slug).nil?
156
165
  end
157
166
  raise LinkError.new("Could not find a free slug; try again", "link_no_slug")
158
167
  end
data/lib/runlight/mcp.rb CHANGED
@@ -318,9 +318,18 @@ module Runlight
318
318
  end
319
319
 
320
320
  # Answers one POST to the MCP endpoint, already authorised.
321
+ # The most a message or batch may weigh; a real one is a few hundred bytes a call.
322
+ MAX_BODY_BYTES = 1024 * 1024
323
+
321
324
  def mcp_response(request, read_api)
322
325
  headers = { "content-type" => "application/json; charset=utf-8", "cache-control" => "no-store" }
323
- parsed, body = Js.parse_json(request.text)
326
+ begin
327
+ text = Body.request_text(request, MAX_BODY_BYTES)
328
+ rescue Http::BodyTooLong
329
+ # Capped here, since not every host caps a request body before it reaches the app.
330
+ return Http::Response.new(Json.encode(rpc_error(nil, -32_600, "Send a smaller message")), status: 413, headers: headers)
331
+ end
332
+ parsed, body = Js.parse_json(text)
324
333
  return Http::Response.new(Json.encode(rpc_error(nil, -32_700, "Send a JSON-RPC message")), status: 400, headers: headers) if !parsed || !Js.object?(body)
325
334
 
326
335
  # Batches were in the 2025-03-26 protocol. Only a short list, so one request cannot start hundreds of