sitegoose 0.3.5 → 0.3.7

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ce69bd61fa38892bea9ea285bebd0688fd618deacd1715ae19ec14e3c7f61f02
4
- data.tar.gz: 83dcc0b5e52dab1c905b45dcb25c20bc242e96cd9c06cde495c5283d2a2812cd
3
+ metadata.gz: f9f39eed7c9a7192621ff68704361c87a26581bf3c0614f2c087d818ab1cb06b
4
+ data.tar.gz: 42a640b58f7029c07493cf7c6c3d574485ace71031d6be81d9467172b5b3f07b
5
5
  SHA512:
6
- metadata.gz: a433baa5a8baa140e54ec32e47778576e8f37a1978216ffd91fe5ec059b2ccab3a187bec96aead0f5d3f54dc12abb1ee33beceb8d0942a99a4804d6ba6593aee
7
- data.tar.gz: 215d28e1a1ac655eb425c112be445495bbdf14dd03ea454dc32bd7b433054b7a3d40fcc9c835557674c1c75ce307d91be707f552e1d5b336f525f80137824c43
6
+ metadata.gz: 884734d7932019e61d89c1d50c3040cdbbe002225993222bb85bf138d84051d90a668de178b83416dce86bb88065886bd5748d0bd1df4c5b73ac0a046eec62d9
7
+ data.tar.gz: e0db299aca1229d854b6da784635f8a41796c8ea817d7dd1ffb32e7f91c46b7e2a01a3a3cd0eee83d11e5dfa2fcdc5e5fee60d2f53c18d8305b897a0245df233
data/README.md CHANGED
@@ -12,25 +12,30 @@ gem "sitegoose"
12
12
 
13
13
  ## Rails
14
14
 
15
- Nothing to add to the middleware stack: the gem's Railtie puts it first.
15
+ Add the gem and put your keys in the environment (site settings has all
16
+ three, ready to copy). That's all: the gem's Railtie puts its middleware
17
+ first.
16
18
 
17
- ```ruby
18
- # config/initializers/sitegoose.rb
19
- SiteGoose.configure(
20
- site_id: "YOUR_SITE_ID",
21
- secret: ENV["ANALYTICS_SITE_SECRET"], # site settings; keep it on the server
22
- endpoint: "https://YOUR_COLLECTOR_URL",
23
- # trust_proxy: 1, # behind Nginx or a load balancer
24
- # trust_proxy: "cloudflare", # every request through Cloudflare
25
- )
19
+ ```bash
20
+ ANALYTICS_SITE_ID=YOUR_SITE_ID
21
+ ANALYTICS_SITE_SECRET=YOUR_SITE_SECRET
22
+ ANALYTICS_ENDPOINT=https://YOUR_COLLECTOR_URL
23
+ # ANALYTICS_TRUST_PROXY=1 # behind Nginx or a load balancer
24
+ # ANALYTICS_TRUST_PROXY=cloudflare # every request through Cloudflare
25
+ # ANALYTICS_SERVER_NAME=api # several services on one site
26
26
  ```
27
27
 
28
- Or keep it in the credentials (`bin/rails credentials:edit`), under
29
- `sitegoose:` with the same keys, or in `config.sitegoose`.
30
- The environment works too: `ANALYTICS_SITE_ID`, `ANALYTICS_SITE_SECRET`,
31
- `ANALYTICS_ENDPOINT`, `ANALYTICS_SERVER_NAME`, `ANALYTICS_TRUST_PROXY`.
32
- Lowest first: the environment, credentials, `config.sitegoose`,
33
- `configure`.
28
+ With `dotenv-rails`, `.env` works as usual: the platform is made on first
29
+ use, after it has loaded.
30
+
31
+ Options in code go in an initializer, or the credentials
32
+ (`bin/rails credentials:edit`, under `sitegoose:`), or `config.sitegoose`.
33
+ Lowest first: the environment, credentials, `config.sitegoose`, `configure`.
34
+
35
+ ```ruby
36
+ # config/initializers/sitegoose.rb (optional)
37
+ SiteGoose.configure(trust_proxy: 1, errors: { capture_logging: true })
38
+ ```
34
39
 
35
40
  Then, on their own:
36
41
 
@@ -47,10 +52,11 @@ In your code: `SiteGoose.track(...)`, or `SiteGoose.platform`.
47
52
  ## Sinatra and other Rack apps
48
53
 
49
54
  ```ruby
50
- use SiteGoose::Middleware,
51
- site_id: "YOUR_SITE_ID", secret: ENV["ANALYTICS_SITE_SECRET"], endpoint: "https://YOUR_COLLECTOR_URL"
55
+ use SiteGoose::Middleware # the keys from ANALYTICS_* in the environment, as for Rails
52
56
  ```
53
57
 
58
+ Or pass them: `use SiteGoose::Middleware, site_id: "...", secret: ENV["ANALYTICS_SITE_SECRET"], endpoint: "https://..."`.
59
+
54
60
  Put it first; added twice (by hand next to the Railtie, or by an engine),
55
61
  the second copy passes requests straight on. Sinatra's route patterns (`/users/:id`) and its error pages are
56
62
  read on their own; set `set :raise_errors, false` (production's default) or
@@ -400,13 +406,20 @@ platform = SiteGoose.platform
400
406
  session = platform.session_id(request) # the visit, from the X-Analytics-Session header
401
407
 
402
408
  platform.track("purchase", { "numeric_value" => "49.90", "currency" => "EUR", "event_uid" => "order-#{order.id}" }, session_id: session)
403
- platform.identify(user.id, session_id: session)
409
+ platform.identify(user.id, session_id: session, traits: { plan: "pro", seats: 5, trial: false }) # traits are optional
404
410
  platform.lead({ "email" => "ana@example.com", "name" => "Ana", "status" => "qualified" })
405
411
  ```
406
412
 
407
413
  `track` sends in the background; `identify` and `lead` wait for the answer
408
414
  (up to 5 seconds).
409
415
 
416
+ **User traits:** `identify` takes optional `traits:`, a hash of name to text,
417
+ number or `true`/`false` (a symbol value is sent as its name). Arrays, hashes
418
+ and other values are left out (and `traits` is left off when nothing is left).
419
+ The collector does the rest: names are lowercased with spaces and dashes as
420
+ `_` (up to 40 letters, digits and `_`), text is cut at 200 characters, values
421
+ that look like an email address are dropped, and at most 20 are kept.
422
+
410
423
  **Link to the visit:** send the tracker's session ID with your site's requests:
411
424
 
412
425
  ```js
@@ -6,7 +6,8 @@
6
6
  #
7
7
  # - track(): events, batched to POST /events/server-events in the background.
8
8
  # Each gets an event_uid, so a retried batch can be told apart from new events.
9
- # - identify(): links the browser's visit to your user ID (/events/identify).
9
+ # - identify(): links the browser's visit to your user ID (/events/identify),
10
+ # with optional traits about the user (plan, seats...).
10
11
  # - lead(): adds or updates a lead (/events/lead).
11
12
  # identify() and lead() wait for the answer (up to 5 seconds).
12
13
 
@@ -79,14 +80,34 @@ module SiteGoose
79
80
  ok
80
81
  end
81
82
 
82
- # Links the visit to your user ID. true when stored.
83
- def identify(user_id, session_id = "")
83
+ # Links the visit to your user ID. true when stored. traits: what you know
84
+ # about the user, name => text, number or true/false
85
+ # ({ plan: "pro", seats: 5 }); anything else is left out, and the
86
+ # collector cleans the names and values.
87
+ def identify(user_id, session_id = "", traits = nil)
84
88
  return false if user_id.to_s.empty? || session_id.to_s.empty? || !@core.on?("analytics")
85
89
 
86
- res = @core.request("analytics", "/events/identify", body: { "user_id" => user_id.to_s, "session_id" => session_id.to_s })
90
+ body = { "user_id" => user_id.to_s, "session_id" => session_id.to_s }
91
+ kept = self.class.scalar_traits(traits)
92
+ body["traits"] = kept unless kept.empty?
93
+ res = @core.request("analytics", "/events/identify", body: body)
87
94
  res ? res.ok? : false
88
95
  end
89
96
 
97
+ # The traits that are text (a symbol as its name), a finite number or
98
+ # true/false, with their names as strings.
99
+ def self.scalar_traits(traits)
100
+ return {} unless traits.is_a?(Hash)
101
+
102
+ traits.each_with_object({}) do |(name, value), kept|
103
+ case value
104
+ when String, Integer, true, false then kept[name.to_s] = value
105
+ when Symbol then kept[name.to_s] = value.to_s
106
+ when Float then kept[name.to_s] = value if value.finite?
107
+ end
108
+ end
109
+ end
110
+
90
111
  # fields: email or phone, and name, status, tags, note, deal fields...
91
112
  # Returns {"status", "lead_id"}, or nil.
92
113
  def lead(fields, session_id = "")
@@ -438,7 +438,24 @@ module SiteGoose
438
438
  nil
439
439
  end
440
440
 
441
- HEADER_NAME = /\A[A-Za-z][A-Za-z0-9-]{0,63}\z/.freeze
441
+ # The nine headers the dashboard can produce (expresscollect/Analytics/
442
+ # platform.js, headersOf), lower case. A list of what's allowed, not of
443
+ # what isn't: whoever got into our servers still couldn't make this app
444
+ # grant another site its users' data (Access-Control-Allow-*), send every
445
+ # page elsewhere (Refresh), log everyone out (Clear-Site-Data) or change
446
+ # what a response is. Shared cases: sdk/protocols/header-cases.json.
447
+ SECURITY_HEADERS = %w[strict-transport-security x-content-type-options x-frame-options referrer-policy
448
+ permissions-policy cross-origin-opener-policy content-security-policy
449
+ content-security-policy-report-only reporting-endpoints].freeze
450
+ HEADER_VALUE = /\A[\x20-\x7e\t]*\z/.freeze
451
+
452
+ # One of SECURITY_HEADERS, in any case, with a value of visible ASCII,
453
+ # spaces and tabs (no line breaks, nothing a server rejects), at most
454
+ # 4,000 characters.
455
+ def self.safe_header?(pair)
456
+ pair.is_a?(Array) && pair.size == 2 && pair[0].is_a?(String) && SECURITY_HEADERS.include?(pair[0].downcase) &&
457
+ pair[1].is_a?(String) && pair[1].size <= 4000 && pair[1].match?(HEADER_VALUE)
458
+ end
442
459
 
443
460
  def sync_switches
444
461
  headers = { "X-Platform-Modules" => @loaded.join(",") }
@@ -454,11 +471,7 @@ module SiteGoose
454
471
  @switches = data["modules"]
455
472
  @flags = data["flags"].is_a?(Hash) ? data["flags"] : {}
456
473
  @maintenance = data["maintenance"].is_a?(Hash) ? data["maintenance"] : { "on" => false }
457
- # Only well-formed headers (no line breaks can get through).
458
- @headers = (data["headers"].is_a?(Array) ? data["headers"] : []).select do |pair|
459
- pair.is_a?(Array) && pair.size == 2 && pair[0].is_a?(String) && pair[0].match?(HEADER_NAME) &&
460
- pair[1].is_a?(String) && !pair[1].include?("\r") && !pair[1].include?("\n") && pair[1].size <= 4000
461
- end
474
+ @headers = (data["headers"].is_a?(Array) ? data["headers"] : []).select { |pair| Core.safe_header?(pair) }
462
475
  @etag = res.headers["etag"].to_s
463
476
  end
464
477
  [MIN_SYNC, (data["sync"].is_a?(Numeric) && data["sync"].positive? ? data["sync"].to_i : RETRY)].max
@@ -496,16 +509,29 @@ module SiteGoose
496
509
  # The characters a path may carry unencoded (RFC 3986).
497
510
  PATH_SAFE = %r{[^A-Za-z0-9/:@!$&'()*+,;=\-._~%]}.freeze
498
511
 
512
+ # A request line's target in origin form (firewall.md, "Matching"), read
513
+ # the way the server's URL parser reads one that doesn't start with "/":
514
+ # a scheme dropped, then, after "//", the authority up to the next "/",
515
+ # "?" or "#", and a "/" put in front of what is left. Puma routes
516
+ # "x:/admin" and "http:/admin" as /admin, so the firewall must not match
517
+ # "/x:/admin". "*" (OPTIONS *) stays as it is.
518
+ def self.origin_form(target)
519
+ target = text(target)
520
+ return target if target.start_with?("/") || target == "*"
521
+
522
+ rest = target.sub(/\A[a-zA-Z][a-zA-Z0-9+.-]*:/, "")
523
+ rest = rest.sub(%r{\A//[^/?#]*}, "")
524
+ rest.start_with?("/") ? rest : "/#{rest}"
525
+ end
526
+
499
527
  # The request target as the visitor sent it, query string and all, which
500
528
  # is what the request rules match (sdk/protocols/firewall.md). Rack's
501
529
  # PATH_INFO is not decoded, and Puma, Unicorn and WEBrick keep the target
502
- # itself as REQUEST_URI, so it is taken as it came; an absolute-form target
503
- # (a proxy request) loses its scheme and host.
530
+ # itself as REQUEST_URI, so it is taken as it came, in origin form.
504
531
  def self.request_target(env)
505
532
  raw = env["REQUEST_URI"]
506
533
  if raw.is_a?(String) && !raw.empty?
507
- target = raw.sub(%r{\A[a-zA-Z][a-zA-Z0-9+.-]*://[^/?#]*}, "")
508
- target = "/#{target}" unless target.start_with?("/") || target.start_with?("*")
534
+ target = origin_form(raw)
509
535
  else
510
536
  target = "#{env['SCRIPT_NAME']}#{env['PATH_INFO']}"
511
537
  target = target.b.gsub(PATH_SAFE) { |c| format("%%%02X", c.ord) }
@@ -515,6 +541,37 @@ module SiteGoose
515
541
  text(target)
516
542
  end
517
543
 
544
+ # The path the app routes on (SCRIPT_NAME + PATH_INFO) when it isn't the
545
+ # path of target (request_target's), else nil. A server whose parser
546
+ # reads a target in a way origin_form doesn't foresee then still has its
547
+ # path checked: the rules match either.
548
+ def self.routed_also(env, target)
549
+ return nil unless env["REQUEST_URI"].is_a?(String) && !env["REQUEST_URI"].empty?
550
+
551
+ routed = "#{env['SCRIPT_NAME']}#{env['PATH_INFO']}"
552
+ routed.empty? || routed == target.split(/[?#]/, 2)[0] ? nil : text(routed)
553
+ end
554
+
555
+ # What a POST asks to be routed as, for the request rules' methods: the
556
+ # X-HTTP-Method-Override header, and a _method in the query string or a
557
+ # form the app already parsed. Rack::MethodOverride, after us, reads the
558
+ # header and the posted form; the body is never read here, so a _method
559
+ # posted in it is matched as POST only.
560
+ def self.method_overrides(env, headers)
561
+ return [] unless env["REQUEST_METHOD"].to_s.upcase == "POST"
562
+
563
+ found = []
564
+ given = header(headers, "x-http-method-override")
565
+ found << given unless given.empty?
566
+ env["QUERY_STRING"].to_s.split("&").each do |pair|
567
+ name, value = pair.split("=", 2)
568
+ found << RequestRules.decode_once(value.to_s) if RequestRules.decode_once(name.to_s) == "_method"
569
+ end
570
+ form = env["rack.request.form_hash"]
571
+ found << form["_method"] if form.is_a?(Hash) && form["_method"].is_a?(String)
572
+ found
573
+ end
574
+
518
575
  # A path with its percent-escapes decoded once, as text (for display and
519
576
  # route names, never for the rules).
520
577
  def self.decode_path(path)
@@ -108,16 +108,27 @@ module SiteGoose
108
108
 
109
109
  # True when the path (no query, lower-cased, "//" as "/") is a probe, as
110
110
  # sent or as the router reads it (";params" dropped, "." and ".."
111
- # resolved, decoded once: "/x/..;/.env" is "/.env").
112
- def self.probe?(path, probes)
111
+ # resolved, decoded once: "/x/..;/.env" is "/.env"). also: the path the
112
+ # app routes on, when the server read the target differently.
113
+ def self.probe?(path, probes, also = nil)
113
114
  return false unless probes
114
115
 
115
- clean = SiteGoose.text(path).split(/[?#]/, 2)[0].to_s.downcase.gsub(%r{/{2,}}, "/")
116
- [clean, RequestRules.normalize_target(path)].uniq.any? do |text|
116
+ texts = [path, also].compact.flat_map do |given|
117
+ [SiteGoose.text(given).split(/[?#]/, 2)[0].to_s.downcase.gsub(%r{/{2,}}, "/"), RequestRules.normalize_target(given)]
118
+ end
119
+ texts.uniq.any? do |text|
117
120
  probes[:exact].key?(text) || probes[:prefix].any? { |p| text.start_with?(p) }
118
121
  end
119
122
  end
120
123
 
124
+ # A request another site made the browser send (firewall.md, "Checking a
125
+ # request"): an <img> or a no-cors fetch on any page can ask for /.env,
126
+ # or for a page 120 times a minute, from the visitor's own address. It
127
+ # is refused but bans no one, and is reported as only watched.
128
+ def self.foreign?(fetch_site)
129
+ %w[cross-site same-site].include?(SiteGoose.text(fetch_site).strip.downcase)
130
+ end
131
+
121
132
  # The rules' page limits -> {exempt:, rules:}, or nil when there are none.
122
133
  # A limit that doesn't parse is left out, not the others: a bad id, a
123
134
  # limit outside 1-100,000, a window outside 1-3,600 seconds, or nothing to
@@ -337,7 +348,9 @@ module SiteGoose
337
348
  next note_over(name, @counter.call(name, limit["window"] * 2).to_i > limit["limit"])
338
349
  end
339
350
 
340
- key = "#{limit['id']} #{limit['window']} #{who}#{limit['each'] ? " #{req[:routed_path]}" : ''}"
351
+ # A page past 2,000 characters is counted by its first 2,000: a key
352
+ # as long as the path would let a crawler fill the table with megabytes.
353
+ key = "#{limit['id']} #{limit['window']} #{who}#{limit['each'] ? " #{req[:routed_path][0, RequestRules::MAX_TEXT]}" : ''}"
341
354
  table = limit["each"] ? @path_counts : @limit_counts
342
355
  if peek
343
356
  entry = table[key]
@@ -454,8 +467,11 @@ module SiteGoose
454
467
  # -> {action: "allow" | "block" | "monitor", rule:, status:}. Allowed
455
468
  # addresses skip every other rule. accept and cookie (the request's
456
469
  # headers) are for the browser check: rule "challenge", status 503,
457
- # answered with challenge_page().
458
- def check(ip, method = "", path = "", user_agent = "", accept = "", cookie = "", now = nil)
470
+ # answered with challenge_page(). fetch_site: the Sec-Fetch-Site header.
471
+ # overrides and also_path: RequestRules.prepare's (SiteGoose.method_overrides
472
+ # and SiteGoose.routed_also).
473
+ def check(ip, method = "", path = "", user_agent = "", accept = "", cookie = "", now = nil,
474
+ fetch_site: "", overrides: nil, also_path: nil)
459
475
  allow = { action: "allow", rule: "", status: 200 }
460
476
  rules = @rules
461
477
  return allow if rules.nil? || !rules[:enabled]
@@ -469,14 +485,18 @@ module SiteGoose
469
485
  { "ip" => ip, "rule" => name, "action" => act, "method" => SiteGoose.text(method, 10),
470
486
  "path" => SiteGoose.text(path).split("?", 2)[0].to_s[0, 300], "user_agent" => SiteGoose.text(user_agent, 300) }
471
487
  end
488
+ # Another site's request: refused as any other, but never a ban.
489
+ bans = !Firewall.foreign?(fetch_site)
472
490
  rule = address_rule(rules, key, ip)
473
- if rule.empty? && Firewall.probe?(path, rules[:probes])
491
+ if rule.empty? && Firewall.probe?(path, rules[:probes], also_path)
474
492
  rule = "probe"
475
493
  # Asking for a secret file: banned here in block mode; the report bans it on the other servers.
476
- ban_here(ip, rules[:probes][:ban]) if action == "block"
494
+ ban_here(ip, rules[:probes][:ban]) if action == "block" && bans
477
495
  end
478
496
  limits = rules[:limits]
479
- req = RequestRules.prepare(method, path, user_agent) if rule.empty? && (!rules[:requests].empty? || limits)
497
+ if rule.empty? && (!rules[:requests].empty? || limits)
498
+ req = RequestRules.prepare(method, path, user_agent, overrides: overrides, also_path: also_path)
499
+ end
480
500
  if rule.empty?
481
501
  matched = RequestRules.match(rules[:requests], method, path, user_agent, req)
482
502
  if matched
@@ -484,7 +504,7 @@ module SiteGoose
484
504
  # A rule the dashboard only watches passes even in block mode; one
485
505
  # that blocks also bans the address here, as a flood does.
486
506
  action = action == "block" && matched["action"] == "block" ? "block" : "monitor"
487
- ban_here(ip, matched["ban"]) if action == "block" && matched["ban"].positive?
507
+ ban_here(ip, matched["ban"]) if action == "block" && matched["ban"].positive? && bans
488
508
  end
489
509
  end
490
510
  # A static file isn't counted toward the page limits or `rate`, only
@@ -517,7 +537,7 @@ module SiteGoose
517
537
  if rule.empty? && rules[:rate] && !goodbot && over_rate?(ip, rules[:rate], peek: static)
518
538
  rule = "rate"
519
539
  # Banned here straight away in block mode, as a probe is; the report bans it on the other servers.
520
- ban_here(ip, rules[:ban]) if action == "block"
540
+ ban_here(ip, rules[:ban]) if action == "block" && bans
521
541
  end
522
542
  if watched
523
543
  if rule.empty?
@@ -541,7 +561,10 @@ module SiteGoose
541
561
  decision = if rule.empty?
542
562
  allow
543
563
  else
544
- report(event.call(rule, action))
564
+ # Reported as watched, so the collector bans no one elsewhere
565
+ # and counts nothing toward `shared`.
566
+ foreign = !bans && (%w[probe rate].include?(rule) || rule.start_with?("request:"))
567
+ report(event.call(rule, foreign ? "monitor" : action))
545
568
  if limit_window
546
569
  # retry_after: the limit's own window, which the 429 carries.
547
570
  { action: action, rule: rule, status: 429, retry_after: limit_window }
@@ -264,9 +264,10 @@ module SiteGoose
264
264
  analytics ? analytics.track(name, fields, session_id) : ""
265
265
  end
266
266
 
267
- def identify(user_id, session_id: "")
267
+ # traits: optional user properties, name => text, number or true/false.
268
+ def identify(user_id, session_id: "", traits: nil)
268
269
  analytics = @modules["analytics"]
269
- analytics ? analytics.identify(user_id, session_id) : false
270
+ analytics ? analytics.identify(user_id, session_id, traits) : false
270
271
  end
271
272
 
272
273
  def lead(fields, session_id: "")
@@ -368,15 +369,18 @@ module SiteGoose
368
369
  # nil. headers: a hash with lowercase names. target: the request target
369
370
  # as sent, query string and all (SiteGoose.request_target). late: a hash
370
371
  # given :static when the request is a static file let through, for
371
- # Firewall#count_static after the response.
372
- def blocked(remote, headers, method, target, late = nil)
372
+ # Firewall#count_static after the response. overrides and also_path:
373
+ # Firewall#check's (SiteGoose.method_overrides, SiteGoose.routed_also).
374
+ def blocked(remote, headers, method, target, late = nil, overrides: nil, also_path: nil)
373
375
  fw = firewall
374
376
  return nil unless fw
375
377
 
376
378
  begin
377
379
  ip = fw.client_ip(remote, headers)
378
380
  decision = fw.check(ip, method, target, SiteGoose.header(headers, "user-agent"),
379
- SiteGoose.header(headers, "accept"), SiteGoose.header(headers, "cookie"))
381
+ SiteGoose.header(headers, "accept"), SiteGoose.header(headers, "cookie"),
382
+ fetch_site: SiteGoose.header(headers, "sec-fetch-site"),
383
+ overrides: overrides, also_path: also_path)
380
384
  return fw.challenge_page(ip, method) if decision[:action] == "block" && decision[:rule] == "challenge"
381
385
 
382
386
  late[:static] = decision[:static] if late && decision[:static]
@@ -413,7 +417,9 @@ module SiteGoose
413
417
 
414
418
  ip = nil
415
419
  late = {}
416
- refused = blocked(remote, headers, method, SiteGoose.request_target(env), late)
420
+ target = SiteGoose.request_target(env)
421
+ refused = blocked(remote, headers, method, target, late, overrides: SiteGoose.method_overrides(env, headers),
422
+ also_path: SiteGoose.routed_also(env, target))
417
423
  if refused
418
424
  ip = firewall ? firewall.client_ip(remote, headers) : remote
419
425
  # A crawler the firewall turned away is still a crawler, and counted
@@ -33,6 +33,19 @@ module SiteGoose
33
33
  # The collector reads these; everything else, cookies above all, stays here.
34
34
  PASS_HEADERS = %w[content-type user-agent accept-language referer origin sec-fetch-site sec-ch-ua
35
35
  sec-ch-ua-mobile sec-ch-ua-platform].freeze
36
+ # What a collector answer may be served as from the site's own domain. Its
37
+ # type comes from the collector, so anything else becomes plain text, and
38
+ # nosniff stops a browser guessing: a server that is no longer ours still
39
+ # can't answer <prefix>/api/... with a page that runs as the customer's own
40
+ # site. Shared cases: sdk/protocols/proxy-answer-cases.json.
41
+ ANSWER_TYPES = %w[application/json text/plain image/webp].freeze
42
+
43
+ def self.answer_type(value)
44
+ given = value.is_a?(String) ? value : ""
45
+ kind = given.split(";", 2).first.to_s.strip.downcase
46
+ ANSWER_TYPES.include?(kind) && given.match?(/\A[\x20-\x7e]*\z/) ? given : "text/plain; charset=utf-8"
47
+ end
48
+
36
49
  SAFE_PATH = %r{\A[A-Za-z0-9/_.-]{1,120}\z}.freeze
37
50
  FILE_PATH = %r{\Av(\d+(?:\.\d+\.\d+)?)/([a-z]+\.js)\z}.freeze
38
51
  # These run on the app's own request threads, so they are short, and a
@@ -238,8 +251,8 @@ module SiteGoose
238
251
  begin
239
252
  answer = fetch(url, method: method, headers: out, body: method == "POST" ? body.to_s : nil)
240
253
  answer.code.to_i >= 500 ? failed : worked
241
- passed = {}
242
- %w[content-type cache-control retry-after].each do |name|
254
+ passed = { "content-type" => Proxy.answer_type(answer["content-type"]), "x-content-type-options" => "nosniff" }
255
+ %w[cache-control retry-after].each do |name|
243
256
  value = answer[name]
244
257
  passed[name] = value if value && !value.empty?
245
258
  end
@@ -31,6 +31,29 @@ module SiteGoose
31
31
  MONGO = /\A([^#{SPACE}]+)(?: ([^#{SPACE}]+))?(?: (.*))?\z/m.freeze
32
32
  # A JavaScript object lists keys that are array indexes first, in order.
33
33
  INDEX_KEY = /\A(?:0|[1-9][0-9]*)\z/.freeze
34
+ # Where "..." may hold a value rather than a name: SQLite takes a
35
+ # double-quoted string as a literal when no column has that name
36
+ # (SQLCipher's PRAGMA key = "x'2DD2..'"), Oracle writes a password as a
37
+ # quoted name, and an unknown database may do either. There "..." is
38
+ # kept only when it reads as a plain name, closed: "email", never
39
+ # "x'2D..'", "N3w P@ss" or an unclosed one.
40
+ VALUE_QUOTES = %w[sqlite oracle other].freeze
41
+ NAME = /\A"[A-Za-z_][A-Za-z0-9_$#]{0,127}"\z/.freeze
42
+
43
+ # A keyword matched in either case, ASCII only, as JavaScript's /i reads
44
+ # it: Ruby's /i would also take the Kelvin sign for a K.
45
+ def self.either_case(word)
46
+ word.gsub(/[A-Za-z]/) { |c| "[#{c.upcase}#{c.downcase}]" }
47
+ end
48
+
49
+ # A password or key written as a name, on any database: Oracle's
50
+ # ALTER USER u IDENTIFIED BY pw and SQLCipher's PRAGMA key = "passphrase".
51
+ # What follows is "?" whether it was a word or a quoted name. The
52
+ # lookbehind is JavaScript's \b, ASCII only: Ruby's \b counts an accented
53
+ # letter as a word character.
54
+ SECRET_NAME = "(\"(?:[^\"]|\"\")*\"?|`(?:[^`]|``)*`?|[^#{SPACE};,()]+)"
55
+ IDENTIFIED = /((?<![A-Za-z0-9_])#{either_case('IDENTIFIED BY ')})#{SECRET_NAME}/.freeze
56
+ PRAGMA_KEY = /((?<![A-Za-z0-9_])#{either_case('PRAGMA ')}(?:[A-Za-z_][A-Za-z0-9_]*\.)?(?:#{either_case('HEX')})?(?:#{either_case('RE')})?#{either_case('KEY')} ?[=(] ?)#{SECRET_NAME}/.freeze
34
57
 
35
58
  module_function
36
59
 
@@ -174,7 +197,8 @@ module SiteGoose
174
197
  out << "?"
175
198
  elsif byte == DOUBLE_QUOTE || byte == BACKTICK
176
199
  skip_quoted(scanner, byte, !literal)
177
- out << sql.byteslice(at, scanner.pos - at)
200
+ run = sql.byteslice(at, scanner.pos - at)
201
+ out << (byte == DOUBLE_QUOTE && VALUE_QUOTES.include?(db) && !run.match?(NAME) ? "?" : run)
178
202
  elsif byte == DOLLAR && !word_before && (tag = scanner.check(DOLLAR_TAG_AT)) && tag.size <= TAG_MAX
179
203
  scanner.pos += tag.bytesize
180
204
  scanner.terminate unless scanner.skip_until(/#{Regexp.escape(tag)}/)
@@ -192,7 +216,7 @@ module SiteGoose
192
216
  out << scanner.getch
193
217
  end
194
218
  end
195
- trim(out.gsub(LIST, "(?)").gsub(ROWS, "(?)"))
219
+ trim(out.gsub(IDENTIFIED, "\\1?").gsub(PRAGMA_KEY, "\\1?").gsub(LIST, "(?)").gsub(ROWS, "(?)"))
196
220
  end
197
221
 
198
222
  # A Mongo filter or pipeline's shape: keys kept, every value "?", and an
@@ -17,14 +17,21 @@
17
17
  module SiteGoose
18
18
  module RequestRules
19
19
  MAX_RULES = 200
20
- # How much of each part a rule may look at. Patterns come from our rules,
21
- # but the text comes from whoever is asking: a bounded slice keeps a bad
22
- # pattern from being a hung request (and Ruby 3.2+ also times it out).
20
+ # How much of a part one regex search may look at. Patterns come from our
21
+ # rules, but the text comes from whoever is asking: a bounded slice keeps
22
+ # a bad pattern from being a hung request (and Ruby 3.2+ also times it
23
+ # out). A longer part is searched in windows of MAX_TEXT, each starting
24
+ # WINDOW_STEP after the last, so a match up to 1,000 characters long is
25
+ # found wherever it sits. The plain matchers read the whole part: a part
26
+ # cut short would let filler carry an attack past them.
23
27
  MAX_TEXT = 2000
28
+ WINDOW_STEP = 1000
24
29
  MAX_REGEX = 200
25
30
  SECTIONS = %w[path query ua].freeze
26
31
  MATCHERS = %w[exact prefix suffix contains].freeze
27
32
  REGEX_TIMEOUT = 0.05
33
+ # What a method override may name (X-HTTP-Method-Override, _method).
34
+ METHOD_TOKEN = /\A[A-Z]{1,20}\z/.freeze
28
35
 
29
36
  module_function
30
37
 
@@ -253,6 +260,9 @@ module SiteGoose
253
260
  elsif safe_pattern?(pattern)
254
261
  begin
255
262
  out["regex"] = compile_regex(pattern)
263
+ # Anchored to the part's start or end: searched only in the window
264
+ # that has it, never at a window's edge in the middle of the part.
265
+ out["anchors"] = [pattern.start_with?("^"), ends_anchored?(pattern)]
256
266
  rescue RegexpError
257
267
  # A pattern we can't compile is dropped; the rule's other parts stay.
258
268
  nil
@@ -261,6 +271,12 @@ module SiteGoose
261
271
  out.empty? ? nil : out
262
272
  end
263
273
 
274
+ # A "$" at the end that isn't escaped: "\$" is a dollar sign, "\\$" a
275
+ # backslash and then the end.
276
+ def ends_anchored?(pattern)
277
+ pattern.end_with?("$") && pattern[0...-1][/\\*\z/].size.even?
278
+ end
279
+
264
280
  # The rules as they will be matched; [] when there are none.
265
281
  def compile(data)
266
282
  given = data.is_a?(Hash) ? data["rules"] : nil
@@ -333,60 +349,100 @@ module SiteGoose
333
349
 
334
350
  # A request target's path (no query string) as the router reads it:
335
351
  # what the probes, the static-file check and the rules' path match too.
352
+ # Resolved from the whole path, never a cut one: "/./././.../login" is
353
+ # "/login" to a router however many "./" it carries.
336
354
  def normalize_target(target)
337
- text = SiteGoose.text(target).split(/[?#]/, 2)[0].to_s
338
- router_path(text[0, MAX_TEXT])[0, MAX_TEXT]
355
+ router_path(SiteGoose.text(target).split(/[?#]/, 2)[0].to_s)
356
+ end
357
+
358
+ # Where a regex is searched in a part this long: the whole part when it
359
+ # fits in one window, else windows starting 0, 1000, 2000, ... until one
360
+ # reaches the end. first / last: the pattern is anchored to the part's
361
+ # start / end, so only the window holding it counts.
362
+ def window_starts(size, first, last)
363
+ return [0] if size <= MAX_TEXT
364
+ return [] if first && last
365
+
366
+ final = (size - MAX_TEXT + WINDOW_STEP - 1) / WINDOW_STEP * WINDOW_STEP
367
+ return [0] if first
368
+ return [final] if last
369
+
370
+ 0.step(final, WINDOW_STEP)
339
371
  end
340
372
 
341
- def regex_hit?(regex, text)
342
- regex.match?(text)
373
+ # One timeout ends the search of the part: the next window would cost as much.
374
+ def regex_hit?(part, text)
375
+ regex = part["regex"]
376
+ first, last = part["anchors"]
377
+ window_starts(text.size, first, last).any? { |start| regex.match?(text[start, MAX_TEXT]) }
343
378
  rescue Regexp::TimeoutError
344
379
  false
345
380
  end
346
381
 
347
- def hits?(part, raw, decoded, routed = nil)
348
- texts = [raw, decoded, routed].compact.uniq
382
+ def hits?(part, texts)
349
383
  texts.any? do |text|
350
384
  next true if part["exact"]&.include?(text)
351
385
  next true if part["prefix"]&.any? { |entry| text.start_with?(entry) }
352
386
  next true if part["suffix"]&.any? { |entry| !entry.empty? && text.end_with?(entry) }
353
387
  next true if part["contains"]&.any? { |entry| !entry.empty? && text.include?(entry) }
354
388
 
355
- part["regex"] ? regex_hit?(part["regex"], text) : false
389
+ part["regex"] ? regex_hit?(part, text) : false
390
+ end
391
+ end
392
+
393
+ # The methods a rule's method list is compared with: the request's own;
394
+ # for a POST, the method it asks to be routed as (Rack::MethodOverride,
395
+ # which runs after us, turns a POST with X-HTTP-Method-Override: DELETE
396
+ # or _method=patch into that); and GET for HEAD, which runs GET routes.
397
+ def methods_of(method, overrides = nil)
398
+ given = method.to_s.upcase
399
+ methods = [given]
400
+ if given == "POST"
401
+ Array(overrides).each do |name|
402
+ name = SiteGoose.text(name).strip.upcase
403
+ methods << name if name.match?(METHOD_TOKEN)
404
+ end
356
405
  end
406
+ methods << "GET" if methods.include?("HEAD")
407
+ methods.uniq
357
408
  end
358
409
 
359
410
  # The request's parts, prepared once for every rule and page limit:
360
411
  # method upper-cased, path raw/decoded/routed, query raw/decoded, ua.
361
- # target is the request target as the server received it, query string and all.
362
- def prepare(method = "", target = "", user_agent = "")
412
+ # target is the request target as the server received it, query string
413
+ # and all. overrides: the method names a POST asks to be routed as.
414
+ # also_path: the path the app routes on (Rack's SCRIPT_NAME + PATH_INFO)
415
+ # when the server read the target differently; a hit on either counts.
416
+ def prepare(method = "", target = "", user_agent = "", overrides: nil, also_path: nil)
363
417
  target = SiteGoose.text(target)
364
- mark = target.index("?")
418
+ # The path ends at the first "?" or "#", the query at a "#": a router
419
+ # drops the fragment, so "/login#1" is the login.
420
+ mark = target.index(/[?#]/)
365
421
  path_part = mark ? target[0, mark] : target
366
- query = mark ? target[(mark + 1)..] : ""
367
- query = query[0, MAX_TEXT]
368
- ua = SiteGoose.text(user_agent)[0, MAX_TEXT].downcase
422
+ query = mark && target[mark] == "?" ? target[(mark + 1)..].split("#", 2)[0].to_s : ""
423
+ paths = [path_part]
424
+ paths << SiteGoose.text(also_path) if also_path && !also_path.to_s.empty? && also_path != path_part
425
+ # Lower-cased after decoding: %55NION decodes to "UNION", which a
426
+ # lower-cased "union select" rule would otherwise never see.
427
+ queries = [query.downcase, decode_once(query).downcase]
369
428
  {
370
429
  method: method.to_s.upcase,
371
- raw_path: normalize_path(path_part[0, MAX_TEXT]),
372
- decoded_path: normalize_path(decode_once(path_part[0, MAX_TEXT])[0, MAX_TEXT]),
373
- # And as the router reads it: "/x;y/../admin" is "/admin" there, so a
374
- # rule on "/admin" catches it; a hit on any of the three counts.
375
- routed_path: router_path(path_part[0, MAX_TEXT])[0, MAX_TEXT],
376
- raw_query: query.downcase,
377
- # Lower-cased after decoding: %55NION decodes to "UNION", which a
378
- # lower-cased "union select" rule would otherwise never see.
379
- decoded_query: decode_once(query)[0, MAX_TEXT].downcase,
380
- ua: ua
430
+ methods: methods_of(method, overrides),
431
+ # Raw, decoded once and as the router reads it: "/x;y/../admin" is
432
+ # "/admin" there, so a rule on "/admin" catches it; a hit on any counts.
433
+ path_texts: paths.flat_map { |p| [normalize_path(p), normalize_path(decode_once(p)), router_path(p)] }.uniq,
434
+ routed_path: router_path(path_part),
435
+ query_texts: queries.uniq,
436
+ ua: SiteGoose.text(user_agent).downcase
381
437
  }
382
438
  end
383
439
 
384
440
  # True when every section the rule names matches the prepared request.
385
441
  def matches?(rule, req)
386
- return false if !rule["methods"].empty? && !rule["methods"].include?(req[:method])
387
- return false if rule["path"] && !hits?(rule["path"], req[:raw_path], req[:decoded_path], req[:routed_path])
388
- return false if rule["query"] && !hits?(rule["query"], req[:raw_query], req[:decoded_query])
389
- return false if rule["ua"] && !hits?(rule["ua"], req[:ua], req[:ua])
442
+ return false if !rule["methods"].empty? && (rule["methods"] & req[:methods]).empty?
443
+ return false if rule["path"] && !hits?(rule["path"], req[:path_texts])
444
+ return false if rule["query"] && !hits?(rule["query"], req[:query_texts])
445
+ return false if rule["ua"] && !hits?(rule["ua"], [req[:ua]])
390
446
 
391
447
  true
392
448
  end
@@ -14,7 +14,17 @@ module SiteGoose
14
14
  # card numbers and tokens are never sent. Fails open: when the check can't
15
15
  # be made, the form is accepted (checked false).
16
16
  class Forms
17
- PRIVATE_FIELD = /pass|card|cvc|cvv|secret|token|ssn|iban|csrf|analytics-shield/i.freeze
17
+ # Fields never sent, by name. Whoever adds the check to a sign-up or a
18
+ # checkout relies on this list: keep it wide. (pass also covers passwd
19
+ # and passport, cc[-_]? the browsers' autocomplete names cc-number,
20
+ # cc-csc and cc-exp.) The same list in every package; (?a) makes \b
21
+ # ASCII, as PHP's and Python's are.
22
+ PRIVATE_FIELD = /(?a)pass|pwd|card|cc[-_]?(num|no|number|csc|exp)|cvc|cvv|cvn|expiry|exp[-_]?(month|year|date)|secret|token|\bauth\b|authoriz|api[-_]?key|otp|mfa|2fa|\bpin\b|security[-_]?code|signature|private|ssn|sin\b|nino|tax[-_]?id|iban|bic|swift|routing|account[-_]?(no|num|number)|dob|birth|licen[cs]e|csrf|nonce|analytics-shield/i.freeze
23
+ # A card number in a field nobody thought to name "card" still must not
24
+ # be sent, so values are checked too: 13-19 digits that pass Luhn are
25
+ # taken out of the text and the rest of the message is kept, so spam is
26
+ # still judged.
27
+ DIGITS = /(?a)\b(?:\d[ -]?){12,18}\d\b/.freeze
18
28
  MAX_FIELDS = 50
19
29
  ANSWER = "analytics-shield"
20
30
 
@@ -39,11 +49,25 @@ module SiteGoose
39
49
  next if label.to_s.match?(PRIVATE_FIELD)
40
50
 
41
51
  value = value.select { |v| v.is_a?(String) }.join(", ") if value.is_a?(Array)
42
- out[SiteGoose.text(label, 100)] = SiteGoose.text(value, 2000) if value.is_a?(String)
52
+ out[SiteGoose.text(label, 100)] = without_card_numbers(SiteGoose.text(value, 2000)) if value.is_a?(String)
43
53
  end
44
54
  out
45
55
  end
46
56
 
57
+ # Anything shaped like a card number, and passing Luhn, as [removed].
58
+ # Luhn is what keeps order numbers and phone numbers readable.
59
+ def self.without_card_numbers(text)
60
+ text.gsub(DIGITS) do |match|
61
+ sum = 0
62
+ match.delete("^0-9").reverse.each_char.with_index do |digit, i|
63
+ n = digit.to_i
64
+ n *= 2 if i.odd?
65
+ sum += n > 9 ? n - 9 : n
66
+ end
67
+ (sum % 10).zero? ? "[removed]" : match
68
+ end
69
+ end
70
+
47
71
  def initialize(core, **_)
48
72
  @core = core
49
73
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SiteGoose
4
- VERSION = "0.3.5"
4
+ VERSION = "0.3.7"
5
5
  end
data/lib/sitegoose.rb CHANGED
@@ -207,8 +207,8 @@ module SiteGoose
207
207
  platform&.track(name, fields, session_id: session_id) || ""
208
208
  end
209
209
 
210
- def identify(user_id, session_id: "")
211
- platform ? platform.identify(user_id, session_id: session_id) : false
210
+ def identify(user_id, session_id: "", traits: nil)
211
+ platform ? platform.identify(user_id, session_id: session_id, traits: traits) : false
212
212
  end
213
213
 
214
214
  def lead(fields, session_id: "")
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sitegoose
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.5
4
+ version: 0.3.7
5
5
  platform: ruby
6
6
  authors:
7
7
  - steviec87
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-07 00:00:00.000000000 Z
11
+ date: 2026-11-14 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rack