devguard-ruby 1.0.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 46c6e68c4e105887c32caf4ace47938d0d91013d95aee234ca6b1a85bdac3e8d
4
+ data.tar.gz: e4a80b0ff5006dd0445a3e81f70cd2284b6440db71bceacb5650642fa166cb74
5
+ SHA512:
6
+ metadata.gz: b63c87a002dc2dd4a64274a37e04652ecbdcc362400901de1f80d4e1c1735ff262e72b2eb9f562f220c3fa9466814775c8b98b674b56bf9d75d36afccfa17e1d
7
+ data.tar.gz: e46d3035dcb2f4c572c6bcfe6dda60c96c37edc906058d1521c46ae06aeae7dd47cf597a7dcdb94660617599c2d246b1c25518b4bbc8d291db2d2fb32f895b20
data/LICENSE ADDED
@@ -0,0 +1,3 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DevGuard Team. All rights reserved.
data/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # DevGuard Ruby Guard (`devguard-ruby`)
2
+
3
+ Rack middleware and Ruby on Rails Railtie for **DevGuard** anti-theft protection, domain allowlisting, invoice milestone autolock enforcement, and SEO-safe HTTP 503 lockouts.
4
+
5
+ Supports **Ruby on Rails**, **Sinatra**, and any standard **Rack** application.
6
+
7
+ ---
8
+
9
+ ## Features
10
+
11
+ - **Zero External Dependencies**: Uses only standard library modules (`net/http`, `uri`, `json`, `thread`, `timeout`).
12
+ - **Fail-Safe Open Policy**: Network timeouts, DNS anomalies, or API downtime will not interrupt client traffic.
13
+ - **Domain Authorization**: Enforces authorized hostnames with full support for wildcard subdomains (`*.example.com`).
14
+ - **Milestone Autolock**: Automatically verifies project licensing status with local thread-safe TTL caching.
15
+ - **SEO-Safe HTTP 503**: Returns status 503 with `Retry-After: 3600` and `X-Robots-Tag: noindex, nofollow, noarchive` during administrative locks.
16
+
17
+ ---
18
+
19
+ ## Installation
20
+
21
+ Add to your Gemfile:
22
+
23
+ ```ruby
24
+ gem "devguard-ruby"
25
+ ```
26
+
27
+ And execute:
28
+
29
+ ```bash
30
+ bundle install
31
+ ```
32
+
33
+ ---
34
+
35
+ ## Configuration & Usage
36
+
37
+ ### 1. Ruby on Rails
38
+
39
+ Create an initializer at `config/initializers/devguard.rb`:
40
+
41
+ ```ruby
42
+ DevGuard.configure do |config|
43
+ config.project_id = ENV["DEVGUARD_PROJECT_ID"]
44
+ config.api_key = ENV["DEVGUARD_API_KEY"]
45
+ config.allowed_domains = ["example.com", "*.example.com"]
46
+ config.fail_safe = :open # :open or :closed
47
+ config.timeout_seconds = 2.5
48
+ config.cache_ttl_seconds = 60
49
+ end
50
+ ```
51
+
52
+ The Railtie automatically inserts `DevGuard::Middleware` into the Rails middleware stack.
53
+
54
+ ### 2. Sinatra
55
+
56
+ ```ruby
57
+ require "sinatra"
58
+ require "devguard"
59
+
60
+ DevGuard.configure do |config|
61
+ config.project_id = "proj_your_project_id"
62
+ config.allowed_domains = ["mysite.com"]
63
+ end
64
+
65
+ use DevGuard::Middleware
66
+
67
+ get "/" do
68
+ "Hello from Sinatra"
69
+ end
70
+ ```
71
+
72
+ ### 3. Plain Rack (`config.ru`)
73
+
74
+ ```ruby
75
+ require "devguard"
76
+
77
+ DevGuard.configure do |config|
78
+ config.project_id = "proj_your_project_id"
79
+ config.allowed_domains = ["mysite.com"]
80
+ end
81
+
82
+ use DevGuard::Middleware
83
+
84
+ run ->(env) { [200, { "Content-Type" => "text/plain" }, ["OK"]] }
85
+ ```
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevGuard
4
+ class Configuration
5
+ DEFAULT_API_URL = "https://api.devguard.uk"
6
+ DEFAULT_TIMEOUT_SECONDS = 2.5
7
+ DEFAULT_CACHE_TTL_SECONDS = 60
8
+ DEFAULT_BYPASS_PATHS = [
9
+ "/assets",
10
+ "/favicon.ico",
11
+ "/robots.txt",
12
+ "/_devguard/health"
13
+ ].freeze
14
+
15
+ attr_accessor :project_id,
16
+ :api_key,
17
+ :api_url,
18
+ :fail_safe,
19
+ :timeout_seconds,
20
+ :cache_ttl_seconds,
21
+ :allowed_domains,
22
+ :bypass_paths,
23
+ :lock_html
24
+
25
+ def initialize
26
+ @project_id = nil
27
+ @api_key = nil
28
+ @api_url = DEFAULT_API_URL
29
+ @fail_safe = :open
30
+ @timeout_seconds = DEFAULT_TIMEOUT_SECONDS
31
+ @cache_ttl_seconds = DEFAULT_CACHE_TTL_SECONDS
32
+ @allowed_domains = []
33
+ @bypass_paths = DEFAULT_BYPASS_PATHS.dup
34
+ @lock_html = nil
35
+ end
36
+
37
+ def fail_safe_open?
38
+ val = @fail_safe.to_s.strip.downcase
39
+ val == "open" || val == "true"
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,297 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+ require "thread"
7
+ require "timeout"
8
+
9
+ module DevGuard
10
+ class Middleware
11
+ LOCKED_STATUSES = %w[locked autolocked payment_past_due].freeze
12
+
13
+ def initialize(app, options = {})
14
+ @app = app
15
+ @options = options || {}
16
+ @cache_mutex = Mutex.new
17
+ @cached_status = nil
18
+ @cached_at = 0.0
19
+ end
20
+
21
+ def call(env)
22
+ path = env["PATH_INFO"] || ""
23
+
24
+ # 1. Bypass paths check
25
+ if bypassed_path?(path)
26
+ return @app.call(env)
27
+ end
28
+
29
+ # 2. Domain verification
30
+ raw_host = env["HTTP_HOST"] || env["SERVER_NAME"] || ""
31
+ unless domain_allowed?(raw_host)
32
+ return [
33
+ 403,
34
+ {
35
+ "Content-Type" => "text/plain",
36
+ "X-DevGuard-Status" => "domain_unauthorized"
37
+ },
38
+ ["Domain unauthorized by DevGuard\n"]
39
+ ]
40
+ end
41
+
42
+ # 3. Status check against DevGuard API
43
+ status = fetch_project_status
44
+ if status_locked?(status)
45
+ return lock_response
46
+ end
47
+
48
+ # 4. Active passthrough
49
+ @app.call(env)
50
+ rescue => e
51
+ handle_failure(e, env)
52
+ end
53
+
54
+ def clear_cache!
55
+ @cache_mutex.synchronize do
56
+ @cached_status = nil
57
+ @cached_at = 0.0
58
+ end
59
+ end
60
+
61
+ private
62
+
63
+ def config
64
+ DevGuard.configuration
65
+ end
66
+
67
+ def project_id
68
+ @options[:project_id] || config.project_id
69
+ end
70
+
71
+ def api_key
72
+ @options[:api_key] || config.api_key
73
+ end
74
+
75
+ def api_url
76
+ @options[:api_url] || config.api_url || Configuration::DEFAULT_API_URL
77
+ end
78
+
79
+ def fail_safe_open?
80
+ val = (@options.key?(:fail_safe) ? @options[:fail_safe] : config.fail_safe).to_s.strip.downcase
81
+ val == "open" || val == "true"
82
+ end
83
+
84
+ def timeout_seconds
85
+ (@options[:timeout_seconds] || config.timeout_seconds || Configuration::DEFAULT_TIMEOUT_SECONDS).to_f
86
+ end
87
+
88
+ def cache_ttl_seconds
89
+ (@options[:cache_ttl_seconds] || config.cache_ttl_seconds || Configuration::DEFAULT_CACHE_TTL_SECONDS).to_f
90
+ end
91
+
92
+ def allowed_domains
93
+ domains = @options[:allowed_domains] || config.allowed_domains || []
94
+ Array(domains)
95
+ end
96
+
97
+ def bypass_paths
98
+ paths = @options[:bypass_paths] || config.bypass_paths || Configuration::DEFAULT_BYPASS_PATHS
99
+ Array(paths)
100
+ end
101
+
102
+ def lock_html_content
103
+ @options[:lock_html] || config.lock_html || default_lock_html(project_id)
104
+ end
105
+
106
+ def bypassed_path?(path)
107
+ bypass_paths.any? { |prefix| path.start_with?(prefix) }
108
+ end
109
+
110
+ def normalize_host(raw_host)
111
+ return "" if raw_host.nil?
112
+
113
+ host = raw_host.to_s.strip.downcase
114
+ return "" if host.empty?
115
+
116
+ # Reject invalid / header injection characters
117
+ return "" if host =~ /[\r\n\0\s\\?#@\/]/
118
+
119
+ # IPv6 bracket notation [::1]:port
120
+ if host.start_with?("[")
121
+ end_bracket = host.index("]")
122
+ return host[1...end_bracket] if end_bracket
123
+ end
124
+
125
+ # Strip port if present
126
+ host = host.split(":").first || ""
127
+
128
+ # Strip trailing dot
129
+ host = host.chop if host.end_with?(".")
130
+
131
+ host
132
+ end
133
+
134
+ def domain_allowed?(raw_host)
135
+ domains = allowed_domains
136
+ return true if domains.empty?
137
+
138
+ normalized = normalize_host(raw_host)
139
+ return false if normalized.empty?
140
+
141
+ domains.any? do |raw_pattern|
142
+ next false if raw_pattern.nil?
143
+
144
+ pat = raw_pattern.to_s.strip.downcase
145
+ next false if pat.empty?
146
+
147
+ if pat == "*"
148
+ true
149
+ elsif pat.start_with?("*.")
150
+ base = normalize_host(pat[2..-1])
151
+ next false if base.empty?
152
+
153
+ normalized == base || normalized.end_with?("." + base)
154
+ else
155
+ normalized_pat = normalize_host(pat)
156
+ !normalized_pat.empty? && normalized == normalized_pat
157
+ end
158
+ end
159
+ end
160
+
161
+ def fetch_project_status
162
+ # Check in-memory cache first
163
+ @cache_mutex.synchronize do
164
+ now = Time.now.to_f
165
+ if @cached_status && (now - @cached_at < cache_ttl_seconds)
166
+ return @cached_status
167
+ end
168
+ end
169
+
170
+ pid = project_id
171
+ return "active" if pid.nil? || pid.to_s.strip.empty?
172
+
173
+ status = query_api(pid)
174
+
175
+ @cache_mutex.synchronize do
176
+ @cached_status = status
177
+ @cached_at = Time.now.to_f
178
+ end
179
+
180
+ status
181
+ end
182
+
183
+ def query_api(pid)
184
+ endpoint = "#{api_url.chomp('/')}/api/v1/projects/#{pid}/status"
185
+ uri = URI.parse(endpoint)
186
+
187
+ http = Net::HTTP.new(uri.host, uri.port)
188
+ http.use_ssl = (uri.scheme == "https")
189
+ http.open_timeout = timeout_seconds
190
+ http.read_timeout = timeout_seconds
191
+
192
+ request = Net::HTTP::Get.new(uri.request_uri)
193
+ request["User-Agent"] = "DevGuard-Ruby/#{DevGuard::VERSION}"
194
+ request["Accept"] = "application/json"
195
+ request["Authorization"] = "Bearer #{api_key}" if api_key && !api_key.to_s.empty?
196
+
197
+ response = http.request(request)
198
+
199
+ if response.is_a?(Net::HTTPSuccess)
200
+ parsed = JSON.parse(response.body) rescue {}
201
+ parsed["status"] ? parsed["status"].to_s.downcase : "active"
202
+ else
203
+ raise "DevGuard API returned HTTP #{response.code}"
204
+ end
205
+ end
206
+
207
+ def status_locked?(status)
208
+ LOCKED_STATUSES.include?(status.to_s.downcase)
209
+ end
210
+
211
+ def lock_response
212
+ [
213
+ 503,
214
+ {
215
+ "Content-Type" => "text/html; charset=utf-8",
216
+ "Retry-After" => "3600",
217
+ "X-Robots-Tag" => "noindex, nofollow, noarchive",
218
+ "X-DevGuard-Status" => "locked"
219
+ },
220
+ [lock_html_content]
221
+ ]
222
+ end
223
+
224
+ def handle_failure(error, env)
225
+ if fail_safe_open?
226
+ log_warning("DevGuard check failed: #{error.message}. Fail-safe open: passing through.")
227
+ @app.call(env)
228
+ else
229
+ log_error("DevGuard check failed: #{error.message}. Fail-safe closed: returning 503.")
230
+ lock_response
231
+ end
232
+ end
233
+
234
+ def log_warning(msg)
235
+ if defined?(Rails.logger) && Rails.logger
236
+ Rails.logger.warn("[DevGuard] #{msg}")
237
+ else
238
+ warn("[DevGuard] #{msg}")
239
+ end
240
+ end
241
+
242
+ def log_error(msg)
243
+ if defined?(Rails.logger) && Rails.logger
244
+ Rails.logger.error("[DevGuard] #{msg}")
245
+ else
246
+ warn("[DevGuard ERROR] #{msg}")
247
+ end
248
+ end
249
+
250
+ def default_lock_html(pid)
251
+ <<~HTML
252
+ <!DOCTYPE html>
253
+ <html lang="en">
254
+ <head>
255
+ <meta charset="utf-8" />
256
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
257
+ <meta name="robots" content="noindex, nofollow, noarchive" />
258
+ <title>Service Unavailable - DevGuard</title>
259
+ <style>
260
+ body {
261
+ background-color: #0b0f19;
262
+ color: #f3f4f6;
263
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
264
+ display: flex;
265
+ align-items: center;
266
+ justify-content: center;
267
+ min-height: 100vh;
268
+ margin: 0;
269
+ padding: 1.5rem;
270
+ box-sizing: border-box;
271
+ }
272
+ .container {
273
+ background: #111827;
274
+ border: 1px solid #1f2937;
275
+ border-radius: 12px;
276
+ max-width: 520px;
277
+ padding: 2.5rem;
278
+ text-align: center;
279
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
280
+ }
281
+ h1 { font-size: 1.5rem; margin-bottom: 1rem; color: #f87171; }
282
+ p { color: #9ca3af; line-height: 1.6; margin-bottom: 1.5rem; }
283
+ .meta { font-size: 0.85rem; color: #6b7280; border-top: 1px solid #1f2937; padding-top: 1rem; }
284
+ </style>
285
+ </head>
286
+ <body>
287
+ <div class="container">
288
+ <h1>Service Temporarily Unavailable</h1>
289
+ <p>This application is temporarily suspended pending administrative milestone verification.</p>
290
+ <div class="meta">DevGuard Protection Active &bull; Project: #{pid || 'Protected'}</div>
291
+ </div>
292
+ </body>
293
+ </html>
294
+ HTML
295
+ end
296
+ end
297
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ if defined?(Rails::Railtie)
4
+ module DevGuard
5
+ class Railtie < ::Rails::Railtie
6
+ initializer "devguard.insert_middleware" do |app|
7
+ app.middleware.use DevGuard::Middleware
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevGuard
4
+ VERSION = "1.0.0"
5
+ end
data/lib/devguard.rb ADDED
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+ require "thread"
7
+ require "timeout"
8
+
9
+ require_relative "devguard/version"
10
+ require_relative "devguard/configuration"
11
+ require_relative "devguard/middleware"
12
+
13
+ if defined?(Rails::Railtie)
14
+ require_relative "devguard/railtie"
15
+ end
16
+
17
+ module DevGuard
18
+ class << self
19
+ def configuration
20
+ @configuration ||= Configuration.new
21
+ end
22
+
23
+ def configure
24
+ yield(configuration) if block_given?
25
+ configuration
26
+ end
27
+
28
+ def reset_configuration!
29
+ @configuration = Configuration.new
30
+ end
31
+ end
32
+ end
metadata ADDED
@@ -0,0 +1,53 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: devguard-ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - DevGuard
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-19 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Zero-dependency Rack middleware providing fail-safe domain locking, automated
14
+ milestone invoice checks, and SEO-safe 503 lockout pages for Ruby on Rails and Sinatra
15
+ applications.
16
+ email:
17
+ - support@devguard.uk
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - LICENSE
23
+ - README.md
24
+ - lib/devguard.rb
25
+ - lib/devguard/configuration.rb
26
+ - lib/devguard/middleware.rb
27
+ - lib/devguard/railtie.rb
28
+ - lib/devguard/version.rb
29
+ homepage: https://devguard.uk
30
+ licenses:
31
+ - MIT
32
+ metadata: {}
33
+ post_install_message:
34
+ rdoc_options: []
35
+ require_paths:
36
+ - lib
37
+ required_ruby_version: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: 2.5.0
42
+ required_rubygems_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0'
47
+ requirements: []
48
+ rubygems_version: 3.0.3.1
49
+ signing_key:
50
+ specification_version: 4
51
+ summary: DevGuard Rack Middleware and Rails Railtie for web milestone licensing and
52
+ anti-theft protection
53
+ test_files: []