active_hashcash 0.5.0 → 0.6.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ef5393e959b8a94792f35bc043c87542568398d3c9444a8e238ba6eafdbb3522
4
- data.tar.gz: 74a51e94325581bf35113f81ccaccd696079bc43cfedc7f734ae5889ab0bb32f
3
+ metadata.gz: 0c53df9a89fac1a14b89fb109520d7b2c35d1455b3b2624d9200186d9a295cf7
4
+ data.tar.gz: d090c36da4d4d17f80b5d7a653cbe2544fc311cdcf63a97bd3b46d1cf944631b
5
5
  SHA512:
6
- metadata.gz: 5d0da77fac447177abebbf04a585927f42d7a100159bf9ab8df1305f1f88b9a394738c03f5a828177dea71f745a941b9bff7a8625c4cc8c5744fc735ef017cc2
7
- data.tar.gz: 6845cb211b39fa5dfe0f0393df05ae7cd6e5b54f5e8f3e27e26a206f9853b026a7a557e0c5dbbf97e2eb1bc5468b4ef418cec31a9e20c98153b8027c13d30947
6
+ metadata.gz: cde7a3bfff3389e1761e461dad1a44a2fd480078fd5fb80362c59f5a4a8f8601feff6a9bf28785bab757abf725213060bffaa724815c8a131b3424f7145bedb5
7
+ data.tar.gz: 3f1c4d3842d4ef2aa871c986d36a9557c3c2b5f94145cdb65375dff56bf3a8e8bd5a24e718783962c3f4a5aaacfef709ae5c2f063b79794fec728ac3c9ef1aab
data/AGENTS.md ADDED
@@ -0,0 +1,9 @@
1
+ # Agents - ActiveHashcas
2
+
3
+ ## Coding instructions
4
+
5
+ - Keep everything as simple as possible
6
+ - Do not extract methods in modules from your initiative
7
+ - Do not use service objects
8
+ - Do not rescue exceptions unless a specific behavior is required
9
+ - Do not test private methods
data/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog of ActiveHashcash
2
2
 
3
+ ## 0.6.0 (2026-09-22)
4
+
5
+ - Penalize bad IPs reported by FireHOL lists. For this feature to do anything you must run the migration and schedule the sync job from a cron:
6
+
7
+ ```
8
+ rails active_hashcash:install:migrations
9
+ rails db:migrate
10
+ ```
11
+
12
+ Then schedule `ActiveHashcash::Reputation::UpdateAllScoresJob.perform_later` anywhere from once per hour to once per day.
13
+
14
+ - Add `ActiveHashcash.throttle_rules` to slow down pushy IPs
15
+
3
16
  ## 0.5.0 (2026-08-08)
4
17
 
5
18
  - Fix stamp date mismatch by using server date instead of client
data/README.md CHANGED
@@ -153,45 +153,101 @@ authenticate :user, -> (u) { u.admin? } do # Supposing there is a User#admin? me
153
153
  end
154
154
  ```
155
155
 
156
- ### Before version 0.3.0
156
+ ## Complexity
157
157
 
158
- You must have Redis in order to prevent double spent stamps. Otherwise it will be useless.
159
- It automatically tries to connect with the environment variables `ACTIVE_HASHCASH_REDIS_URL` or `REDIS_URL`.
160
- You can also manually set the URL with `ActiveHashcash.redis_url = redis://user:password@localhost:6379`.
158
+ Complexity controls the base proof-of-work difficulty.
159
+ Increasing by one doubles the work time.
160
+ By default its value is 20 and you can change it with `ActiveHashcash.bits = 24` or by overriding the method `hashcash_bits` in the controller.
161
161
 
162
- You should call `ActiveHashcash::Store#clean` once a day, to remove expired stamps.
162
+ ### Penalties
163
163
 
164
- To upgrade from 0.2.0 you must run the migration :
164
+ To improve protection, a penalty is added for pushy and bad IPs.
165
165
 
166
+ ### For pushy IPs
167
+
168
+ A penalty is added for IPs which submit valid stamps too fast.
169
+ The goal is to slow down attackers using a botnet.
170
+ The penalty rules can be defined like this.
171
+
172
+ ```ruby
173
+ ActiveHashcash.throttle_rules = [
174
+ {period: 1.hour, rate: 0.5},
175
+ {period: 24.hours, rate: 0.25}
176
+ ]
166
177
  ```
167
- rails active_hashcash:install:migrations
168
- rails db:migrate
178
+
179
+ For every valid stamp sent less than an hour ago, a penalty of 0.5 is added.
180
+ Then, for every valid stamp sent between 1 and 24 hours ago a penalty of 0.25 is added.
181
+ Thus, if an IP sent 1 stamp one minute ago, and 3 others few hours ago, it adds a complexity of `(1 * 0.5 + 3 * 0.25).floor # => 1`.
182
+ So next hashcash must have a complexity of `ActiveHashcash.bits + 1`.
183
+
184
+ If you have many users behind the same IP, such as a NAT, you can either lower the rates or disable the penalty.
185
+ In your controller, override the method `hashcash_throttle_penalty`:
186
+
187
+ ```ruby
188
+ class SessionController < ApplicationController
189
+ include ActiveHashcash
190
+
191
+ def hashcash_throttle_penalty
192
+ # Only the base complexity (ActiveHashcash.bits) will apply for people with IP 1.2.3.4
193
+ hashcash_ip_address == "1.2.3.4" ? 0 : super
194
+ end
195
+ end
169
196
  ```
170
197
 
171
- ## Complexity
198
+ Or, if someone is attacking you from a specific country:
199
+
200
+ ```ruby
201
+ class SessionController < ApplicationController
202
+ include ActiveHashcash
203
+
204
+ def hashcash_throttle_penalty
205
+ geoip.country(hashcash_ip_address).country_code == "XX" ? super + 2 : super
206
+ end
207
+ end
208
+ ```
209
+
210
+ ### For IPs with poor reputation
211
+
212
+ The following lists are used to increase the complexity for bad IPs:
172
213
 
173
- Complexity is the most important parameter. By default its value is 20 and requires most of the time 5 to 20 seconds to be solved on a decent laptop.
174
- The user won't wait that long, since he needs to fill the form while the problem is solving.
175
- However, if your application includes people with slow and old devices, then consider lowering this value, to 16 or 18.
214
+ - [FireHOL abusers 1 day](https://iplists.firehol.org/files/firehol_abusers_1d.netset)
215
+ - [FireHOL abusers 30 days](https://iplists.firehol.org/files/firehol_abusers_30d.netset)
216
+ - [FireHOL anonymous](https://iplists.firehol.org/files/firehol_anonymous.netset) (Tor, public proxies, etc.)
217
+ - [FireHOL level 1](https://iplists.firehol.org/files/firehol_level1.netset)
218
+ - [FireHOL level 2](https://iplists.firehol.org/files/firehol_level2.netset)
219
+ - [FireHOL level 3](https://iplists.firehol.org/files/firehol_level3.netset)
220
+ - [FireHOL level 4](https://iplists.firehol.org/files/firehol_level4.netset)
176
221
 
177
- You can change the minimum complexity with `ActiveHashcash.bits = 20`.
222
+ The lists are stored in `ActiveHashcash::Reputation::IPv4Address` (single IPs) and `ActiveHashcash::Reputation::IPv4Range` (CIDR ranges). For this feature to do anything you must run the migration and schedule `ActiveHashcash::Reputation::UpdateAllScoresJob.perform_later` from a cron anywhere from once per hour to once per day.
223
+ If you update too often you might be blocked.
224
+ Updating reputation for ranges probably will not work before Rails 7.1 because of composite primary key + `upsert_all`.
178
225
 
179
- Since version 0.3.0, the complexity increases with the number of stamps spent during le last 24H from the same IP address.
180
- Thus it becomes very efficient to slow down brute force attacks.
226
+ If you don't trust these external lists, don't schedule that job and delete all records of `ActiveHashcash::Reputation::IPv4Address` and `ActiveHashcash::Reputation::IPv4Range`.
181
227
 
182
- ## Testing
228
+ The penalty can be high enough that the proof of work is almost impossible.
229
+ That is useful to neutralize bots.
183
230
 
184
- Browser tests submit the real form, so they have to compute a real stamp. At the default 16 bits this adds noticeable time to every submission and slows down your suite. Drop the complexity in the test environment so it finishes almost instantly:
231
+ ## Testing Your Application
232
+
233
+ Browser tests submit the real form, so they have to compute a real stamp. At the default complexity this adds noticeable time to every submission and slows down your suite. Drop the complexity in the test environment so it finishes almost instantly:
185
234
 
186
235
  ```ruby
187
236
  # spec/rails_helper.rb (RSpec) or test/test_helper.rb (Minitest)
188
- ActiveHashcash.bits = 2
237
+ ActiveHashcash.bits = 1
189
238
  ```
190
239
 
191
- In controller tests, provide the hashcash this way:
240
+ Use `ActiveHashcash::Stamp.mint` to submit hashcash to your sensitive forms:
192
241
 
193
242
  ```ruby
194
- post(url, params: {hashcash: ActiveHashcash::Stamp.mint(host).to_s})
243
+ class SessionControllerTest < ActionDispatch::IntegrationTest
244
+ def test_create
245
+ # ...
246
+ hashcash = ActiveHashcash::Stamp.mint(host).to_s
247
+ post(session_path, params: {email: email, password: password, hashcash: hashcash})
248
+ # ...
249
+ end
250
+ end
195
251
  ```
196
252
 
197
253
  ## Limitations
@@ -202,6 +258,21 @@ A synchronous tight loop avoids the per-call async overhead of `crypto.subtle.di
202
258
 
203
259
  No `crypto.subtle` or secure context (HTTPS) is required, so it works in any environment including plain HTTP during development.
204
260
 
261
+ ### Before version 0.3.0
262
+
263
+ You must have Redis in order to prevent double spent stamps. Otherwise it will be useless.
264
+ It automatically tries to connect with the environment variables `ACTIVE_HASHCASH_REDIS_URL` or `REDIS_URL`.
265
+ You can also manually set the URL with `ActiveHashcash.redis_url = redis://user:password@localhost:6379`.
266
+
267
+ You should call `ActiveHashcash::Store#clean` once a day, to remove expired stamps.
268
+
269
+ To upgrade from 0.2.0 you must run the migration :
270
+
271
+ ```
272
+ rails active_hashcash:install:migrations
273
+ rails db:migrate
274
+ ```
275
+
205
276
  ## Contributing
206
277
 
207
278
  Bug reports and pull requests are welcome on GitHub at https://github.com/BaseSecrete/active_hashcash.
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveHashcash
4
+ module Reputation
5
+ class CleanupJob < ApplicationJob
6
+ def perform
7
+ IPv4Address.delete_zero_scores
8
+ IPv4Range.delete_zero_scores
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveHashcash
4
+ module Reputation
5
+ class UpdateAbuseScoreJob < UpdateScoreJob
6
+ # Higher scores first so upsert_score keeps the max via uniq.
7
+ URLS = {
8
+ "https://iplists.firehol.org/files/firehol_abusers_1d.netset" => 2,
9
+ "https://iplists.firehol.org/files/firehol_abusers_30d.netset" => 1
10
+ }.freeze
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveHashcash
4
+ module Reputation
5
+ class UpdateAllScoresJob < ApplicationJob
6
+ DEFAULT_JOBS = [UpdateAbuseScoreJob, UpdateAnonymousScoreJob, UpdateAttackScoreJob, CleanupJob].freeze
7
+
8
+ def perform(jobs = DEFAULT_JOBS.dup)
9
+ if (job = jobs.shift)
10
+ job.perform_now
11
+ self.class.perform_later(jobs) if jobs.any?
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveHashcash
4
+ module Reputation
5
+ class UpdateAnonymousScoreJob < UpdateScoreJob
6
+ URLS = {
7
+ "https://iplists.firehol.org/files/firehol_anonymous.netset" => 1
8
+ }.freeze
9
+
10
+ def max_body_size
11
+ 50.megabytes
12
+ end
13
+
14
+ def read_timeout
15
+ 20
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveHashcash
4
+ module Reputation
5
+ class UpdateAttackScoreJob < UpdateScoreJob
6
+ # Higher scores first so upsert_score keeps the max via uniq.
7
+ URLS = {
8
+ "https://iplists.firehol.org/files/firehol_level1.netset" => 4,
9
+ "https://iplists.firehol.org/files/firehol_level2.netset" => 3,
10
+ "https://iplists.firehol.org/files/firehol_level3.netset" => 2,
11
+ "https://iplists.firehol.org/files/firehol_level4.netset" => 1
12
+ }.freeze
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+ require "net/http"
5
+ require "uri"
6
+
7
+ module ActiveHashcash
8
+ module Reputation
9
+ class UpdateScoreJob < ApplicationJob
10
+ def perform
11
+ entries = self.class::URLS.flat_map { |url, score| normalize(fetch(url), score) }
12
+ raise "Empty list" if entries.empty?
13
+ addresses, ranges = entries.partition { |ip, _| ip.prefix == 32 }
14
+ IPv4Address.transaction do
15
+ IPv4Address.reset_score(score_name, addresses)
16
+ IPv4Range.reset_score(score_name, ranges)
17
+ end
18
+ end
19
+
20
+ def score_name
21
+ self.class.name[/Update(\w*)ScoreJob/, 1].downcase.to_sym
22
+ end
23
+
24
+ def fetch(url)
25
+ uri = URI(url)
26
+ body = +""
27
+
28
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: open_timeout, read_timeout: read_timeout) do |http|
29
+ http.request(Net::HTTP::Get.new(uri)) do |response|
30
+ response.error! unless response.is_a?(Net::HTTPSuccess)
31
+ response.read_body do |chunk|
32
+ body << chunk
33
+ raise "Response body exceeds #{max_body_size} bytes" if body.bytesize > max_body_size
34
+ end
35
+ end
36
+ end
37
+
38
+ body
39
+ end
40
+
41
+ def open_timeout
42
+ 5
43
+ end
44
+
45
+ def read_timeout
46
+ 10
47
+ end
48
+
49
+ def max_body_size
50
+ 10.megabytes
51
+ end
52
+
53
+ def normalize(body, score)
54
+ body.each_line.filter_map do |line|
55
+ next if (line = line.strip).blank? || line.start_with?("#", ";")
56
+ next if (ip = IPAddr.new(line)).private? || ip.loopback? || ip.link_local? || !ip.ipv4? || ip.prefix < IPv4Range::MIN_PREFIX
57
+ [ip, score]
58
+ rescue IPAddr::InvalidAddressError
59
+ next
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+
5
+ module ActiveHashcash
6
+ module Reputation
7
+ class IPv4Address < ApplicationRecord
8
+ self.table_name = "active_hashcash_reputation_ipv4_addresses"
9
+
10
+ validates :id, presence: true, length: {is: 4}
11
+ validates :anonymous_score, inclusion: {in: 0..1}
12
+ validates :abuse_score, inclusion: {in: 0..2}
13
+ validates :attack_score, inclusion: {in: 0..4}
14
+
15
+ def self.scores(ip)
16
+ abuse, anonymous, attack = where(id: ActiveRecord::Type::Binary.new.serialize(IPAddr.new(ip).hton)).pick(:abuse_score, :anonymous_score, :attack_score)
17
+ {abuse: abuse || 0, anonymous: anonymous || 0, attack: attack || 0}
18
+ rescue IPAddr::InvalidAddressError
19
+ {abuse: 0, anonymous: 0, attack: 0}
20
+ end
21
+
22
+ def self.reset_score(name, entries)
23
+ column = :"#{name}_score"
24
+ entries.uniq! { |ip, _| ip }
25
+ transaction do
26
+ where(column => 1..).update_all(column => 0)
27
+ entries.each_slice(10_000) { |batch| upsert_score(column, batch) }
28
+ end
29
+ end
30
+
31
+ def self.upsert_score(column, entries)
32
+ upsert_all(
33
+ entries.map { |ip, value| {id: ip.hton, column => value} },
34
+ record_timestamps: false,
35
+ update_only: [column]
36
+ )
37
+ end
38
+
39
+ def self.delete_zero_scores
40
+ where(anonymous_score: 0, abuse_score: 0, attack_score: 0).delete_all
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+
5
+ module ActiveHashcash
6
+ module Reputation
7
+ class IPv4Range < ApplicationRecord
8
+ self.table_name = "active_hashcash_reputation_ipv4_ranges"
9
+
10
+ MIN_PREFIX = 16 # Reject nets too large
11
+
12
+ validates :first_address, :last_address, presence: true, length: {is: 4}
13
+ validates :anonymous_score, inclusion: {in: 0..1}
14
+ validates :abuse_score, inclusion: {in: 0..2}
15
+ validates :attack_score, inclusion: {in: 0..4}
16
+
17
+ # PK probes for ancestor CIDRs /MIN_PREFIX../32 (wider prefixes are ignored).
18
+ scope :by_address, -> (string) {
19
+ ip = IPAddr.new(string)
20
+ binary = ActiveRecord::Type::Binary.new
21
+ pairs = (MIN_PREFIX..32).map do |prefix|
22
+ range = IPAddr.new("#{ip}/#{prefix}").to_range
23
+ [binary.serialize(range.first.hton), binary.serialize(range.last.hton)]
24
+ end
25
+ where(pairs.map { "(first_address = ? AND last_address = ?)" }.join(" OR "), *pairs.flatten)
26
+ }
27
+
28
+ def self.scores(ip)
29
+ abuse, anonymous, attack = by_address(ip).pick(Arel.sql("max(abuse_score), max(anonymous_score), max(attack_score)"))
30
+ {abuse: abuse || 0, anonymous: anonymous || 0, attack: attack || 0}
31
+ rescue IPAddr::InvalidAddressError
32
+ {abuse: 0, anonymous: 0, attack: 0}
33
+ end
34
+
35
+ def self.reset_score(name, entries)
36
+ column = :"#{name}_score"
37
+ entries.uniq! { |ip, _| ip }
38
+ transaction do
39
+ where(column => 1..).update_all(column => 0)
40
+ entries.each_slice(10_000) { |batch| upsert_score(column, batch) }
41
+ end
42
+ end
43
+
44
+ def self.upsert_score(column, entries)
45
+ upsert_all(
46
+ entries.map do |ip, value|
47
+ range = ip.to_range
48
+ {first_address: range.first.hton, last_address: range.last.hton, column => value}
49
+ end,
50
+ record_timestamps: false,
51
+ update_only: [column]
52
+ )
53
+ end
54
+
55
+ def self.delete_zero_scores
56
+ where(anonymous_score: 0, abuse_score: 0, attack_score: 0).delete_all
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveHashcash
4
+ module Reputation
5
+ def self.scores(ip)
6
+ address = IPv4Address.scores(ip)
7
+ range = IPv4Range.scores(ip)
8
+ {
9
+ abuse: [address[:abuse], range[:abuse]].max,
10
+ anonymous: [address[:anonymous], range[:anonymous]].max,
11
+ attack: [address[:attack], range[:attack]].max
12
+ }
13
+ end
14
+ end
15
+ end
@@ -26,6 +26,24 @@ module ActiveHashcash
26
26
  scope
27
27
  end
28
28
 
29
+ # Returns stamp counts per period for disjoint windows.
30
+ # +periods+ must be sorted shortest to longest (as ensured by ActiveHashcash.throttle_rules=).
31
+ def self.sum_by_periods(periods)
32
+ return [] if periods.blank?
33
+
34
+ cutoffs = periods.map(&:ago)
35
+ columns = cutoffs.each_with_index.map do |cutoff, index|
36
+ if index.zero?
37
+ sanitize_sql(["sum(CASE WHEN created_at >= ? THEN 1 ELSE 0 END)", cutoff])
38
+ else
39
+ previous_cutoff = cutoffs[index - 1]
40
+ sanitize_sql(["sum(CASE WHEN created_at < ? AND created_at >= ? THEN 1 ELSE 0 END)", previous_cutoff, cutoff])
41
+ end
42
+ end.join(", ")
43
+
44
+ Array.wrap(where(created_at: cutoffs.min..).pluck(Arel.sql(columns)).first)
45
+ end
46
+
29
47
  # Verify and save the hashcash stamp.
30
48
  # Saving in the database prevent from double spending the same stamp.
31
49
  def self.spend(string, resource, bits, date, options = {})
@@ -0,0 +1,54 @@
1
+ # IPv4 reputation addresses and ranges are stored in the database.
2
+ # This migration creates the tables for ActiveHashcash::Reputation::IPv4Address
3
+ # and ActiveHashcash::Reputation::IPv4Range.
4
+ # Run the following commands to add them to your Rails application:
5
+ #
6
+ # rails active_hashcash:install:migrations
7
+ # rails db:migrate
8
+ #
9
+ class CreateActiveHashcashReputationIpv4s < ActiveRecord::Migration[5.2]
10
+ def up
11
+ # uint32 would have been the best choice for storing IPv4, but PostgreSQL does not support unsigned integers.
12
+ # So, 4-byte binary column is a trade off for best efficiency compatible with PostgreSQL, MySQL and SQLite.
13
+ create_table :active_hashcash_reputation_ipv4_addresses, id: false do |t|
14
+ t.binary :id, limit: 4, null: false, primary_key: true
15
+ t.integer :abuse_score, limit: 1, null: false, default: 0
16
+ t.integer :anonymous_score, limit: 1, null: false, default: 0
17
+ t.integer :attack_score, limit: 1, null: false, default: 0
18
+ end
19
+
20
+ create_table :active_hashcash_reputation_ipv4_ranges, primary_key: [:first_address, :last_address] do |t|
21
+ t.binary :first_address, limit: 4, null: false
22
+ t.binary :last_address, limit: 4, null: false
23
+ t.integer :abuse_score, limit: 1, null: false, default: 0
24
+ t.integer :anonymous_score, limit: 1, null: false, default: 0
25
+ t.integer :attack_score, limit: 1, null: false, default: 0
26
+ end
27
+
28
+ # For SQLite, save space by suffixing the CREATE TABLE statements by `WITHOUT ROWID`:
29
+ # execute <<-SQL
30
+ # CREATE TABLE IF NOT EXISTS "active_hashcash_reputation_ipv4_addresses" (
31
+ # "id" blob(4) NOT NULL,
32
+ # "abuse_score" integer(1) DEFAULT 0 NOT NULL,
33
+ # "anonymous_score" integer(1) DEFAULT 0 NOT NULL,
34
+ # "attack_score" integer(1) DEFAULT 0 NOT NULL,
35
+ # PRIMARY KEY ("id")
36
+ # ) WITHOUT ROWID;
37
+ # SQL
38
+ # execute <<-SQL
39
+ # CREATE TABLE IF NOT EXISTS "active_hashcash_reputation_ipv4_ranges" (
40
+ # "first_address" blob(4) NOT NULL,
41
+ # "last_address" blob(4) NOT NULL,
42
+ # "abuse_score" integer(1) DEFAULT 0 NOT NULL,
43
+ # "anonymous_score" integer(1) DEFAULT 0 NOT NULL,
44
+ # "attack_score" integer(1) DEFAULT 0 NOT NULL,
45
+ # PRIMARY KEY ("first_address", "last_address")
46
+ # ) WITHOUT ROWID;
47
+ # SQL
48
+ end
49
+
50
+ def down
51
+ drop_table :active_hashcash_reputation_ipv4_addresses
52
+ drop_table :active_hashcash_reputation_ipv4_ranges
53
+ end
54
+ end
@@ -3,5 +3,11 @@ module ActiveHashcash
3
3
  config.assets.paths << File.expand_path("../..", __FILE__) if config.respond_to?(:assets)
4
4
 
5
5
  isolate_namespace ActiveHashcash
6
+
7
+ initializer "active_hashcash.inflections" do
8
+ ActiveSupport::Inflector.inflections(:en) do |inflect|
9
+ inflect.acronym "IPv4"
10
+ end
11
+ end
6
12
  end
7
13
  end
@@ -1,3 +1,3 @@
1
1
  module ActiveHashcash
2
- VERSION = "0.5.0"
2
+ VERSION = "0.6.0"
3
3
  end
@@ -14,8 +14,8 @@ require "active_hashcash/engine"
14
14
  # before_action :check_hashcash, only: :create
15
15
  # end
16
16
  #
17
- # Your are welcome to override most of the methods to customize to your needs.
18
- # For example, if your app runs behind a loab balancer you should probably override #hashcash_ip_address.
17
+ # You are welcome to override most of the methods to customize to your needs.
18
+ # For example, if your app runs behind a load balancer you should probably override #hashcash_ip_address.
19
19
  #
20
20
  module ActiveHashcash
21
21
  extend ActiveSupport::Concern
@@ -28,10 +28,41 @@ module ActiveHashcash
28
28
 
29
29
  # This is base complexity.
30
30
  # Consider lowering it to not exclude people with old and slow devices.
31
- mattr_accessor :bits, instance_accessor: false, default: 16
31
+ mattr_accessor :bits, instance_accessor: false, default: 20
32
+
33
+ # Flexible complexity penalty rules applied to pushy IP addresses.
34
+ # Each rule must be a hash with:
35
+ # - :period => time window considered (e.g. 5.minutes, 1.hour, 1.day)
36
+ # - :rate => multiplier applied to the number of stamps in that window
37
+ # Assignment sorts rules from shortest to longest period.
38
+ #
39
+ # Example:
40
+ # ActiveHashcash.throttle_rules = [
41
+ # {period: 5.minutes, rate: 0.5},
42
+ # {period: 1.hour, rate: 0.34},
43
+ # {period: 1.day, rate: 0.25}
44
+ # ]
45
+ mattr_reader :throttle_rules, instance_accessor: false, default: [
46
+ {period: 1.hour, rate: 0.5},
47
+ {period: 24.hours, rate: 0.25}
48
+ ]
49
+
50
+ def self.throttle_rules=(rules)
51
+ rules&.each do |rule|
52
+ raise ArgumentError, "ActiveHashcash.throttle_rules period must be present" if rule[:period].nil?
53
+ raise ArgumentError, "ActiveHashcash.throttle_rules rate must be >= 0" if rule[:rate].to_f.negative?
54
+ end
55
+ @@throttle_rules = rules && rules.sort_by { |rule| rule[:period] }
56
+ end
32
57
 
33
58
  mattr_accessor :date_format, instance_accessor: false, default: "%y%m%d"
34
59
 
60
+ # Base controller class used by ActiveHashcash helpers/integration.
61
+ # Override this if your application subclasses the default Rails
62
+ # `ActionController::Base` (e.g. to apply common behavior across controllers).
63
+
64
+ # By default ActiveHashcash extends `ActionController::Base`, but you can change it to any controller,
65
+ # such as `AdminController` to handle authentication for the dashboard.
35
66
  mattr_accessor :base_controller_class, default: "ActionController::Base"
36
67
 
37
68
  # Call that method via a before_action when the form is submitted:
@@ -60,7 +91,7 @@ module ActiveHashcash
60
91
  request.remote_ip
61
92
  end
62
93
 
63
- # Return current request path to be saved to the sucessful ActiveHash::Stamp.
94
+ # Return current request path to be saved to the successful ActiveHashcash::Stamp.
64
95
  # If multiple forms are protected via hashcash this is an interesting info.
65
96
  def hashcash_request_path
66
97
  request.path
@@ -73,20 +104,29 @@ module ActiveHashcash
73
104
 
74
105
  # This is the resource used to build the hashcash stamp.
75
106
  # By default the host name is returned.
76
- # It' should be good for most cases and prevent from reusing the same stamp between sites.
107
+ # It should be good for most cases and prevent from reusing the same stamp between sites.
77
108
  def hashcash_resource
78
109
  ActiveHashcash.resource || request.host
79
110
  end
80
111
 
81
112
  # Returns the complexity, the higher the slower it is.
82
- # Complexity is increased logarithmicly for each IP during the last 24H to slowdown brute force attacks.
83
- # The minimun value returned is ActiveHashcash.bits.
113
+ # Eventually adds penalties for bad and pushy IPs.
84
114
  def hashcash_bits
85
- if (previous_stamp_count = ActiveHashcash::Stamp.where(ip_address: hashcash_ip_address).where(created_at: 1.day.ago..).count) > 0
86
- (ActiveHashcash.bits + Math.log2(previous_stamp_count)).floor
87
- else
88
- ActiveHashcash.bits
89
- end
115
+ (ActiveHashcash.bits + hashcash_throttle_penalty + hashcash_reputation_penalty).floor
116
+ end
117
+
118
+ # Compute a penalty for pushy IPs.
119
+ # The penalty rules can be defined with `ActiveHashcash.throttle_rules`.
120
+ def hashcash_throttle_penalty
121
+ rules = ActiveHashcash.throttle_rules || []
122
+ periods = rules.map { |rule| rule[:period] }
123
+ counts = ActiveHashcash::Stamp.where(ip_address: hashcash_ip_address).sum_by_periods(periods)
124
+ rules.each_with_index.sum { |rule, index| counts[index].to_i * rule[:rate].to_f }
125
+ end
126
+
127
+ # Compute a reputation penalty for the current IP.
128
+ def hashcash_reputation_penalty
129
+ Reputation.scores(hashcash_ip_address).values.sum * 4
90
130
  end
91
131
 
92
132
  # Override if you want to rename the hashcash param.
@@ -111,7 +151,7 @@ module ActiveHashcash
111
151
  # Override me for your own needs.
112
152
  end
113
153
 
114
- # Call it inside the form that have to be protected and don't forget to initialize the JavaScript Hascash.setup().
154
+ # Call it inside the form that have to be protected and don't forget to initialize the JavaScript Hashcash.setup().
115
155
  # Unless you need something really special, you should not need to override this method.
116
156
  #
117
157
  # <% form_for model do |form| %>
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: active_hashcash
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.0
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Alexis Bernard
@@ -31,6 +31,7 @@ executables: []
31
31
  extensions: []
32
32
  extra_rdoc_files: []
33
33
  files:
34
+ - AGENTS.md
34
35
  - CHANGELOG.md
35
36
  - LICENSE.txt
36
37
  - README.md
@@ -45,8 +46,17 @@ files:
45
46
  - app/helpers/active_hashcash/application_helper.rb
46
47
  - app/helpers/active_hashcash/stamps_helper.rb
47
48
  - app/jobs/active_hashcash/application_job.rb
49
+ - app/jobs/active_hashcash/reputation/cleanup_job.rb
50
+ - app/jobs/active_hashcash/reputation/update_abuse_score_job.rb
51
+ - app/jobs/active_hashcash/reputation/update_all_scores_job.rb
52
+ - app/jobs/active_hashcash/reputation/update_anonymous_score_job.rb
53
+ - app/jobs/active_hashcash/reputation/update_attack_score_job.rb
54
+ - app/jobs/active_hashcash/reputation/update_score_job.rb
48
55
  - app/mailers/active_hashcash/application_mailer.rb
49
56
  - app/models/active_hashcash/application_record.rb
57
+ - app/models/active_hashcash/reputation.rb
58
+ - app/models/active_hashcash/reputation/ipv4_address.rb
59
+ - app/models/active_hashcash/reputation/ipv4_range.rb
50
60
  - app/models/active_hashcash/stamp.rb
51
61
  - app/views/active_hashcash/addresses/index.html.erb
52
62
  - app/views/active_hashcash/assets/_logo.svg.erb
@@ -71,6 +81,7 @@ files:
71
81
  - config/locales/pt.yml
72
82
  - config/routes.rb
73
83
  - db/migrate/20240215143453_create_active_hashcash_stamps.rb
84
+ - db/migrate/20260831130000_create_active_hashcash_reputation_ipv4s.rb
74
85
  - lib/active_hashcash.rb
75
86
  - lib/active_hashcash/engine.rb
76
87
  - lib/active_hashcash/version.rb