devfortress-sdk 0.1.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 (39) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +4 -0
  3. data/Gemfile +7 -0
  4. data/LICENSE +63 -0
  5. data/README.md +121 -0
  6. data/Rakefile +11 -0
  7. data/lib/devfortress/agent_adapter.rb +185 -0
  8. data/lib/devfortress/agent_loop_detector.rb +167 -0
  9. data/lib/devfortress/agent_output_exfiltration_detector.rb +115 -0
  10. data/lib/devfortress/agent_security.rb +431 -0
  11. data/lib/devfortress/alias_verify.rb +87 -0
  12. data/lib/devfortress/api_key_aliasing.rb +240 -0
  13. data/lib/devfortress/bounded_map.rb +80 -0
  14. data/lib/devfortress/circuit_breaker.rb +149 -0
  15. data/lib/devfortress/classifier.rb +133 -0
  16. data/lib/devfortress/client.rb +380 -0
  17. data/lib/devfortress/client_ip.rb +28 -0
  18. data/lib/devfortress/clock_drift_detector.rb +71 -0
  19. data/lib/devfortress/credential_isolation.rb +340 -0
  20. data/lib/devfortress/credential_vault.rb +93 -0
  21. data/lib/devfortress/delivery_result.rb +9 -0
  22. data/lib/devfortress/graduated_rate_limiter.rb +270 -0
  23. data/lib/devfortress/internal_closed_loop_engine.rb +658 -0
  24. data/lib/devfortress/license_manager.rb +297 -0
  25. data/lib/devfortress/observer.rb +62 -0
  26. data/lib/devfortress/prompt_injection_filter.rb +73 -0
  27. data/lib/devfortress/response_webhook_client.rb +165 -0
  28. data/lib/devfortress/shadow_agent_registry.rb +123 -0
  29. data/lib/devfortress/signer.rb +134 -0
  30. data/lib/devfortress/telemetry.rb +407 -0
  31. data/lib/devfortress/tier_gate.rb +294 -0
  32. data/lib/devfortress/tool_call_sequence_validator.rb +126 -0
  33. data/lib/devfortress/transport.rb +31 -0
  34. data/lib/devfortress/unified_audit_trail.rb +213 -0
  35. data/lib/devfortress/version.rb +5 -0
  36. data/lib/devfortress/webhook_verification.rb +9 -0
  37. data/lib/devfortress/webhook_verifier.rb +93 -0
  38. data/lib/devfortress.rb +96 -0
  39. metadata +110 -0
@@ -0,0 +1,294 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevFortress
4
+ # Tier Gating & Feature Access Control.
5
+ #
6
+ # Enforces feature access based on subscription tier:
7
+ #
8
+ # Starter: Observe events; response is webhook-dispatched and
9
+ # self-executed by the customer (no platform-side blocking)
10
+ # Pro: View + block via external CL only — no internal/hybrid,
11
+ # not even as an add-on (Package A, 2026-08-28)
12
+ # Team: External, internal, and hybrid all available as first-class
13
+ # capabilities (default: hybrid) — the entry point for
14
+ # internal/hybrid CL under Package A
15
+ # Enterprise: Can select internal, external, or hybrid
16
+ # (default: hybrid with internal backup, external primary)
17
+ #
18
+ # Mirrors packages/devfortress-sdk/src/tier-gate.ts. Depends on
19
+ # LicenseManager resolving the active subscription tier from the
20
+ # platform (see LicenseManager#license_state.tier).
21
+ class TierGate
22
+ TierGateSnapshot = Struct.new(
23
+ :tier, :hybrid_addon_enabled, :daily_event_count, :daily_reset_time,
24
+ :monthly_event_count, :monthly_reset_time, :snapshot_timestamp,
25
+ keyword_init: true
26
+ )
27
+
28
+ TIER_CAPABILITIES = {
29
+ "starter" => {
30
+ can_observe: true, can_block: false, allowed_modes: %w[external], default_mode: "external",
31
+ hybrid_is_addon: false, internal_as_backup_only: false, can_configure_rules: false,
32
+ can_access_audit: false, can_manage_webhooks: false, max_events_per_day: 10_000, max_blocked_ips: 0,
33
+ # CV-S2: Starter gets Tier 1 deterministic rules only
34
+ icl_max_tier: 1, air_gap_enabled: false, custom_rules_enabled: false,
35
+ # CV-S3: 50K events/month (matches SUBSCRIPTION_PRICING, Option B pricing)
36
+ max_events_per_month: 50_000,
37
+ # CV-S4/S5/S6
38
+ platform_alerts: false, shared_state: false, compliance_evidence: false,
39
+ }.freeze,
40
+ "pro" => {
41
+ can_observe: true, can_block: true,
42
+ # Package A (2026-08-28): Pro gets External CL only, at no point in
43
+ # time does it get ICL/hybrid — differentiation comes from
44
+ # platform-executed response, post-auth detection, alias
45
+ # isolation, and AI insights, never from CL mode depth.
46
+ # Internal/Hybrid access starts at Team.
47
+ allowed_modes: %w[external], default_mode: "external", hybrid_is_addon: false,
48
+ internal_as_backup_only: false, can_configure_rules: false, can_access_audit: true,
49
+ can_manage_webhooks: true, max_events_per_day: 100_000, max_blocked_ips: 1_000,
50
+ # CV-S2: Pro has no ICL access — External CL only (Package A)
51
+ icl_max_tier: 0, air_gap_enabled: false, custom_rules_enabled: false,
52
+ # CV-S3: 75K events/month (matches SUBSCRIPTION_PRICING, Option B pricing)
53
+ max_events_per_month: 75_000,
54
+ # CV-S4/S5/S6: platform alerts + shared state, no compliance evidence (Enterprise only)
55
+ platform_alerts: true, shared_state: true, compliance_evidence: false,
56
+ }.freeze,
57
+ "team" => {
58
+ can_observe: true, can_block: true,
59
+ # Package A (2026-08-28): Team is the new entry point for
60
+ # Internal/Hybrid CL — takes on the capability profile Pro used to
61
+ # have, but as a first-class capability (no add-on gate, no
62
+ # backup-only limit).
63
+ allowed_modes: %w[external internal hybrid], default_mode: "hybrid", hybrid_is_addon: false,
64
+ internal_as_backup_only: false, can_configure_rules: false, can_access_audit: true,
65
+ can_manage_webhooks: true, max_events_per_day: 0, max_blocked_ips: 5_000,
66
+ # CV-S2: Team gets Tier 1 + Tier 2 ML (same ceiling Pro used to have)
67
+ icl_max_tier: 2, air_gap_enabled: false, custom_rules_enabled: false,
68
+ # CV-S3: 100K events/month (matches SUBSCRIPTION_PRICING, Option B pricing)
69
+ max_events_per_month: 100_000,
70
+ # CV-S4/S5/S6: platform alerts + shared state + compliance evidence
71
+ # (matches Team's advertised compliance PDF reports)
72
+ platform_alerts: true, shared_state: true, compliance_evidence: true,
73
+ }.freeze,
74
+ "enterprise" => {
75
+ can_observe: true, can_block: true, allowed_modes: %w[external internal hybrid],
76
+ default_mode: "hybrid", hybrid_is_addon: false, internal_as_backup_only: false,
77
+ can_configure_rules: true, can_access_audit: true, can_manage_webhooks: true,
78
+ max_events_per_day: 0, max_blocked_ips: 0,
79
+ # CV-S2: Enterprise gets all tiers + air-gap + custom rules
80
+ icl_max_tier: 3, air_gap_enabled: true, custom_rules_enabled: true,
81
+ # CV-S3: Unlimited events/month
82
+ max_events_per_month: 0,
83
+ # CV-S4/S5/S6: full alert channels, full shared state, compliance evidence
84
+ platform_alerts: true, shared_state: true, compliance_evidence: true,
85
+ }.freeze,
86
+ }.freeze
87
+
88
+ attr_reader :tier, :capabilities
89
+
90
+ def initialize(tier, hybrid_addon_enabled: false)
91
+ raise ArgumentError, "DevFortress: unknown subscription tier #{tier.inspect}" unless TIER_CAPABILITIES.key?(tier)
92
+
93
+ @tier = tier
94
+ @capabilities = TIER_CAPABILITIES.fetch(tier).dup
95
+ @hybrid_addon_enabled = hybrid_addon_enabled
96
+ @daily_event_count = 0
97
+ @daily_reset_time = self.class.day_start_ms
98
+ @monthly_event_count = 0
99
+ @monthly_reset_time = self.class.month_start_ms
100
+ end
101
+
102
+ # Gets the effective closed-loop mode for this tier. Validates the
103
+ # requested mode against tier permissions.
104
+ def effective_mode(requested_mode = nil)
105
+ return @capabilities[:default_mode] unless requested_mode
106
+ return @capabilities[:default_mode] unless @capabilities[:allowed_modes].include?(requested_mode)
107
+
108
+ # Pro tier: hybrid requires add-on
109
+ if @tier == "pro" && requested_mode == "hybrid" && @capabilities[:hybrid_is_addon] && !@hybrid_addon_enabled
110
+ return "external"
111
+ end
112
+
113
+ requested_mode
114
+ end
115
+
116
+ def can_block?
117
+ @capabilities[:can_block]
118
+ end
119
+
120
+ # Checks whether the daily event limit has been reached.
121
+ def check_event_limit
122
+ day_start = self.class.day_start_ms
123
+ if @daily_reset_time < day_start
124
+ @daily_event_count = 0
125
+ @daily_reset_time = day_start
126
+ end
127
+
128
+ return { allowed: true, remaining: Float::INFINITY } if (@capabilities[:max_events_per_day]).zero?
129
+
130
+ remaining = @capabilities[:max_events_per_day] - @daily_event_count
131
+ { allowed: remaining.positive?, remaining: [0, remaining].max }
132
+ end
133
+
134
+ # Records an event (for limit tracking).
135
+ def record_event
136
+ @daily_event_count += 1
137
+ end
138
+
139
+ # Checks whether a specific feature is available for this tier.
140
+ def has_feature?(feature)
141
+ value = @capabilities[feature.to_sym]
142
+ case value
143
+ when true, false then value
144
+ when Numeric then true
145
+ when Array then !value.empty?
146
+ else false
147
+ end
148
+ end
149
+
150
+ # Validates a blocking action against tier permissions. Returns an
151
+ # error message if not allowed, nil if allowed.
152
+ def validate_block_action(_action)
153
+ return nil if @capabilities[:can_block]
154
+
155
+ "Blocking is not available on the #{@tier} tier. Upgrade to Pro or Enterprise to enable blocking."
156
+ end
157
+
158
+ # Validates a mode selection against tier permissions. Returns an
159
+ # error message if not allowed, nil if allowed.
160
+ def validate_mode(mode)
161
+ unless @capabilities[:allowed_modes].include?(mode)
162
+ return "The '#{mode}' mode is not available on the #{@tier} tier. " \
163
+ "Allowed modes: #{@capabilities[:allowed_modes].join(', ')}."
164
+ end
165
+
166
+ if @tier == "pro" && mode == "hybrid" && @capabilities[:hybrid_is_addon] && !@hybrid_addon_enabled
167
+ return "Hybrid mode requires the hybrid add-on on the Pro tier. Enable it in your subscription settings."
168
+ end
169
+
170
+ nil
171
+ end
172
+
173
+ # Resets daily/monthly counters — test-only, mirrors the Node source's
174
+ # _reset() (also documented there as @internal/test-only).
175
+ def reset_for_testing!
176
+ @daily_event_count = 0
177
+ @daily_reset_time = 0
178
+ @monthly_event_count = 0
179
+ @monthly_reset_time = 0
180
+ end
181
+
182
+ # ── CV-S2: Tiered ICL Capabilities ──────────────────────────
183
+
184
+ # Gets the maximum ICL tier available for this subscription.
185
+ # - 0: No ICL (monitor-only)
186
+ # - 1: Tier 1 deterministic rules only
187
+ # - 2: Tier 1 + Tier 2 ML scoring
188
+ # - 3: All tiers + air-gap + custom rules
189
+ def max_icl_tier
190
+ @capabilities[:icl_max_tier]
191
+ end
192
+
193
+ def icl_tier_available?(tier)
194
+ @capabilities[:icl_max_tier] >= tier
195
+ end
196
+
197
+ def air_gap_enabled?
198
+ @capabilities[:air_gap_enabled]
199
+ end
200
+
201
+ def custom_rules_configurable?
202
+ @capabilities[:custom_rules_enabled]
203
+ end
204
+
205
+ # ── CV-S3: Monthly Event Quotas ──────────────────────────────
206
+
207
+ def check_monthly_quota
208
+ month_start = self.class.month_start_ms
209
+ if @monthly_reset_time < month_start
210
+ @monthly_event_count = 0
211
+ @monthly_reset_time = month_start
212
+ end
213
+
214
+ limit = @capabilities[:max_events_per_month]
215
+ return { allowed: true, remaining: Float::INFINITY, limit: 0 } if limit.zero?
216
+
217
+ remaining = limit - @monthly_event_count
218
+ { allowed: remaining.positive?, remaining: [0, remaining].max, limit: limit }
219
+ end
220
+
221
+ def record_monthly_event
222
+ @monthly_event_count += 1
223
+ end
224
+
225
+ # Gets monthly usage stats for the telemetry heartbeat.
226
+ def monthly_usage
227
+ limit = @capabilities[:max_events_per_month]
228
+ {
229
+ used: @monthly_event_count,
230
+ limit: limit,
231
+ percent_used: limit.positive? ? ((@monthly_event_count.to_f / limit) * 100).round : 0,
232
+ }
233
+ end
234
+
235
+ # ── CV-S4/S5/S6: Platform Feature Checks ────────────────────
236
+
237
+ # CV-S4: ICL mode can only log to console/filesystem.
238
+ def platform_alerts?
239
+ @capabilities[:platform_alerts]
240
+ end
241
+
242
+ # CV-S5: ICL maintains per-instance state only.
243
+ def shared_state?
244
+ @capabilities[:shared_state]
245
+ end
246
+
247
+ # CV-S6: ICL provides raw logs but no compliance formatting.
248
+ def compliance_evidence?
249
+ @capabilities[:compliance_evidence]
250
+ end
251
+
252
+ # ── S15: Usage Metering Persistence ─────────────────────────
253
+
254
+ # Snapshots mutable state for persistence across restarts. Caller
255
+ # should serialize to JSON and store in DB/file.
256
+ def to_snapshot
257
+ TierGateSnapshot.new(
258
+ tier: @tier, hybrid_addon_enabled: @hybrid_addon_enabled, daily_event_count: @daily_event_count,
259
+ daily_reset_time: @daily_reset_time, monthly_event_count: @monthly_event_count,
260
+ monthly_reset_time: @monthly_reset_time, snapshot_timestamp: (Time.now.to_f * 1000).to_i
261
+ )
262
+ end
263
+
264
+ # Restores state from a previously saved snapshot. Ignores the
265
+ # snapshot's counters if the tier has changed or if they are stale
266
+ # (past their reset boundary).
267
+ def self.from_snapshot(snapshot, hybrid_addon_enabled: nil)
268
+ gate = new(
269
+ snapshot.tier,
270
+ hybrid_addon_enabled: snapshot.hybrid_addon_enabled.nil? ? hybrid_addon_enabled : snapshot.hybrid_addon_enabled
271
+ )
272
+
273
+ if snapshot.daily_reset_time >= day_start_ms
274
+ gate.instance_variable_set(:@daily_event_count, snapshot.daily_event_count)
275
+ gate.instance_variable_set(:@daily_reset_time, snapshot.daily_reset_time)
276
+ end
277
+
278
+ if snapshot.monthly_reset_time >= month_start_ms
279
+ gate.instance_variable_set(:@monthly_event_count, snapshot.monthly_event_count)
280
+ gate.instance_variable_set(:@monthly_reset_time, snapshot.monthly_reset_time)
281
+ end
282
+
283
+ gate
284
+ end
285
+
286
+ def self.day_start_ms(time = Time.now)
287
+ Time.new(time.year, time.month, time.day, 0, 0, 0, time.utc_offset).to_i * 1000
288
+ end
289
+
290
+ def self.month_start_ms(time = Time.now)
291
+ Time.new(time.year, time.month, 1, 0, 0, 0, time.utc_offset).to_i * 1000
292
+ end
293
+ end
294
+ end
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevFortress
4
+ # Tool-Call Sequence Validator (A7).
5
+ #
6
+ # Validates AI agent tool calls against an authorized directed acyclic
7
+ # graph (DAG). Detects out-of-sequence tool calls that indicate prompt
8
+ # injection attacks — e.g., an agent jumping directly to `place_order`
9
+ # without first calling `add_to_cart`. Graduated response: log →
10
+ # rate-limit → block → revoke session. Mirrors
11
+ # packages/devfortress-sdk/src/tool-call-sequence-validator.ts.
12
+ #
13
+ # The graph is a Hash of tool_name => { requires: [...], max_calls:,
14
+ # risk_level: }.
15
+ class ToolCallSequenceValidator
16
+ MAX_SESSIONS = 50_000
17
+
18
+ def initialize(graph:, max_violations: 3, violation_window_ms: 300_000, graduated_response: true)
19
+ @graph = graph
20
+ @max_violations = max_violations
21
+ @violation_window_ms = violation_window_ms
22
+ @graduated_response = graduated_response
23
+ @sessions = {}
24
+ end
25
+
26
+ def validate(session_id, tool_name, timestamp: nil)
27
+ session = get_or_create_session(session_id)
28
+ now = timestamp || now_ms
29
+
30
+ session[:violations] = session[:violations].select { |v| now - v[:timestamp] < @violation_window_ms }
31
+
32
+ graph_node = @graph[tool_name]
33
+
34
+ unless graph_node
35
+ session[:violations] << { timestamp: now, tool: tool_name, reason: "unknown_tool" }
36
+ return build_result(session, false, "unknown_tool", tool_name, [])
37
+ end
38
+
39
+ missing_prereqs = (graph_node[:requires] || []).reject { |req| session[:call_history].include?(req) }
40
+ unless missing_prereqs.empty?
41
+ session[:violations] << { timestamp: now, tool: tool_name, reason: "missing_prerequisites: #{missing_prereqs.join(', ')}" }
42
+ return build_result(session, false, "out_of_sequence", tool_name, missing_prereqs)
43
+ end
44
+
45
+ current_calls = session[:call_counts][tool_name] || 0
46
+ max_calls = graph_node[:max_calls]
47
+ if max_calls && max_calls.positive? && current_calls >= max_calls
48
+ session[:violations] << { timestamp: now, tool: tool_name, reason: "max_calls_exceeded: #{current_calls}/#{max_calls}" }
49
+ return build_result(session, false, "max_calls_exceeded", tool_name, [])
50
+ end
51
+
52
+ session[:call_history] << tool_name
53
+ session[:call_counts][tool_name] = current_calls + 1
54
+
55
+ {
56
+ allowed: true, reason: "valid_sequence", action: "allow", prompt_injection_likely: false,
57
+ violation_count: session[:violations].length, call_history: session[:call_history].dup,
58
+ }
59
+ end
60
+
61
+ def reset_session(session_id)
62
+ @sessions.delete(session_id)
63
+ end
64
+ alias clear_session reset_session
65
+
66
+ def history(session_id)
67
+ session = @sessions[session_id]
68
+ session ? session[:call_history].dup : []
69
+ end
70
+
71
+ def session_stats(session_id)
72
+ session = @sessions[session_id]
73
+ return { exists: false, call_count: 0, violation_count: 0, history: [] } unless session
74
+
75
+ { exists: true, call_count: session[:call_history].length, violation_count: session[:violations].length,
76
+ history: session[:call_history].dup }
77
+ end
78
+
79
+ def destroy
80
+ @sessions.clear
81
+ end
82
+
83
+ private
84
+
85
+ def get_or_create_session(session_id)
86
+ session = @sessions[session_id]
87
+ unless session
88
+ @sessions.delete(@sessions.first[0]) if @sessions.size >= MAX_SESSIONS
89
+ session = { call_history: [], call_counts: {}, violations: [], created_at: now_ms }
90
+ @sessions[session_id] = session
91
+ end
92
+ session
93
+ end
94
+
95
+ def build_result(session, allowed, reason, tool_name, missing_prerequisites)
96
+ violation_count = session[:violations].length
97
+
98
+ action = if @graduated_response
99
+ if violation_count >= @max_violations
100
+ "revoke_session"
101
+ elsif violation_count >= 2
102
+ "block"
103
+ elsif violation_count >= 1
104
+ "rate_limit"
105
+ else
106
+ "log"
107
+ end
108
+ else
109
+ "block"
110
+ end
111
+
112
+ graph_node = @graph[tool_name]
113
+ prompt_injection_likely = reason == "out_of_sequence" && %w[high critical].include?(graph_node&.[](:risk_level)&.to_s)
114
+
115
+ {
116
+ allowed: allowed, reason: reason, action: action, prompt_injection_likely: prompt_injection_likely,
117
+ violation_count: violation_count, call_history: session[:call_history].dup,
118
+ missing_prerequisites: missing_prerequisites.empty? ? nil : missing_prerequisites,
119
+ }
120
+ end
121
+
122
+ def now_ms
123
+ (Time.now.to_f * 1000).to_i
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+
6
+ module DevFortress
7
+ TransportResponse = Struct.new(:status_code, :body, keyword_init: true)
8
+
9
+ class TransportError < StandardError; end
10
+
11
+ # The default transport: Net::HTTP, no redirects followed, path sent as written.
12
+ class Transport
13
+ def send_request(method, url, headers, body, timeout)
14
+ uri = URI.parse(url)
15
+ http = Net::HTTP.new(uri.host, uri.port)
16
+ http.use_ssl = uri.scheme == "https"
17
+ http.open_timeout = timeout
18
+ http.read_timeout = timeout
19
+ http.write_timeout = timeout if http.respond_to?(:write_timeout=)
20
+
21
+ request = Net::HTTP.const_get(method.to_s.capitalize).new(uri.request_uri)
22
+ headers.each { |k, v| request[k] = v }
23
+ request.body = body if body && !body.empty?
24
+
25
+ response = http.request(request)
26
+ TransportResponse.new(status_code: response.code.to_i, body: response.body.to_s)
27
+ rescue StandardError => e
28
+ raise TransportError, e.message
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,213 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevFortress
4
+ # Unified Audit Trail (CL-M3).
5
+ #
6
+ # Mirrors packages/devfortress-sdk/src/unified-audit.ts. Merges internal
7
+ # and external closed-loop audit events into a single in-memory
8
+ # timeline with consistent fields regardless of source.
9
+ #
10
+ # NOTE on tamper-evidence: this is an in-memory log only -- it is not
11
+ # cryptographically signed or hash-chained, and neither is Node's own
12
+ # UnifiedAuditTrail. The HMAC-signed, hash-chained tamper-evident audit
13
+ # trail (TODO 265/266/272) is a separate, server-side Next.js module
14
+ # (lib/audit-trail-signer.ts) operating directly on the LiveThreatEvent
15
+ # Postgres table. It has no SDK-side analog in any language, including
16
+ # Node, so this port does not and cannot provide tamper-evidence either.
17
+ class UnifiedAuditTrail
18
+ DEDUP_WINDOW_SECONDS = 5
19
+ DEDUP_MAP_CAP = 10_000
20
+ DEFAULT_MAX_ENTRIES = 100_000
21
+
22
+ Entry = Struct.new(
23
+ :event_id, :timestamp, :source, :tier, :decision, :score, :severity,
24
+ :latency_ms, :ip, :path, :method, :matched_rules, :user_id, :agent_id,
25
+ :session_id, :fallback_mode, :meta,
26
+ keyword_init: true
27
+ ) do
28
+ def to_h_ordered
29
+ {
30
+ event_id: event_id, timestamp: timestamp, source: source, tier: tier,
31
+ decision: decision, score: score, severity: severity, latency_ms: latency_ms,
32
+ ip: ip, path: path, method: method, matched_rules: matched_rules,
33
+ user_id: user_id, agent_id: agent_id, session_id: session_id,
34
+ fallback_mode: fallback_mode, meta: meta,
35
+ }
36
+ end
37
+ end
38
+
39
+ def initialize(max_entries: DEFAULT_MAX_ENTRIES, on_entry: nil, debug: false)
40
+ @max_entries = max_entries
41
+ @on_entry = on_entry
42
+ @debug = debug
43
+ @mutex = Mutex.new
44
+ @entries = []
45
+ @recent_event_ids = {}
46
+ @stats = {
47
+ internal_decisions: 0, external_decisions: 0, hybrid_decisions: 0,
48
+ fallback_events: 0, total_blocks: 0, total_allows: 0, total_rate_limits: 0,
49
+ internal_latency_sum: 0.0, external_latency_sum: 0.0,
50
+ }
51
+ end
52
+
53
+ # Records an audit entry from any source. S27: the same event_id
54
+ # within the 5s dedup window is merged (external overrides internal),
55
+ # not duplicated.
56
+ def record(entry)
57
+ fire_entry = nil
58
+
59
+ @mutex.synchronize do
60
+ now = Time.now
61
+ existing = @recent_event_ids[entry.event_id]
62
+ if existing && (now - existing) < DEDUP_WINDOW_SECONDS
63
+ if entry.source == :external || entry.source == "external"
64
+ idx = @entries.index { |e| e.event_id == entry.event_id && (e.source == :internal || e.source == "internal") }
65
+ if idx
66
+ merged = @entries[idx].to_h_ordered.merge(entry.to_h_ordered).merge(source: :hybrid)
67
+ @entries[idx] = Entry.new(**merged)
68
+ warn "[DF Audit] DEDUP: merged #{entry.event_id} (external overrides internal)" if @debug
69
+ end
70
+ end
71
+ next
72
+ end
73
+
74
+ @recent_event_ids[entry.event_id] = now
75
+ if @recent_event_ids.size > DEDUP_MAP_CAP
76
+ cutoff = now - DEDUP_WINDOW_SECONDS
77
+ @recent_event_ids.delete_if { |_id, ts| ts < cutoff }
78
+ end
79
+
80
+ @entries.shift((@max_entries * 0.1).floor) if @entries.size >= @max_entries
81
+ @entries << entry
82
+ update_stats(entry)
83
+ fire_entry = entry
84
+ end
85
+
86
+ return unless fire_entry
87
+
88
+ if @on_entry
89
+ begin
90
+ @on_entry.call(fire_entry)
91
+ rescue StandardError
92
+ # Callback errors must not break the audit trail.
93
+ end
94
+ end
95
+
96
+ return unless @debug
97
+
98
+ warn "[DF Audit] #{entry.source}:tier#{entry.tier} #{entry.decision} " \
99
+ "score=#{entry.score} #{entry.ip} #{entry.method} #{entry.path} (#{entry.latency_ms}ms)"
100
+ end
101
+
102
+ # Queries audit entries with filters.
103
+ def query(source: nil, decision: nil, ip: nil, user_id: nil, agent_id: nil,
104
+ min_score: nil, since: nil, limit: 100)
105
+ result = @mutex.synchronize { @entries.dup }
106
+
107
+ result = result.select { |e| e.source.to_s == source.to_s } if source
108
+ result = result.select { |e| e.decision.to_s == decision.to_s } if decision
109
+ result = result.select { |e| e.ip == ip } if ip
110
+ result = result.select { |e| e.user_id == user_id } if user_id
111
+ result = result.select { |e| e.agent_id == agent_id } if agent_id
112
+ result = result.select { |e| e.score >= min_score } if min_score
113
+ result = result.select { |e| e.timestamp >= since } if since
114
+
115
+ limit && limit > 0 ? result.last(limit) : result
116
+ end
117
+
118
+ # Returns aggregated statistics.
119
+ def get_stats
120
+ stats, total = @mutex.synchronize { [@stats.dup, @entries.size] }
121
+
122
+ avg_internal = stats[:internal_decisions].positive? ? (stats[:internal_latency_sum] / stats[:internal_decisions]).round : 0
123
+ avg_external = stats[:external_decisions].positive? ? (stats[:external_latency_sum] / stats[:external_decisions]).round : 0
124
+
125
+ {
126
+ total: total,
127
+ internal_decisions: stats[:internal_decisions],
128
+ external_decisions: stats[:external_decisions],
129
+ hybrid_decisions: stats[:hybrid_decisions],
130
+ fallback_events: stats[:fallback_events],
131
+ total_blocks: stats[:total_blocks],
132
+ total_allows: stats[:total_allows],
133
+ total_rate_limits: stats[:total_rate_limits],
134
+ avg_internal_latency_ms: avg_internal,
135
+ avg_external_latency_ms: avg_external,
136
+ }
137
+ end
138
+
139
+ # Returns source:decision counts, for dashboard visualization.
140
+ def get_decision_distribution
141
+ entries = @mutex.synchronize { @entries.dup }
142
+ dist = {}
143
+ entries.each do |e|
144
+ key = "#{e.source}:#{e.decision}"
145
+ dist[key] = (dist[key] || 0) + 1
146
+ end
147
+ dist
148
+ end
149
+
150
+ # Returns latency histogram buckets.
151
+ def get_latency_histogram
152
+ entries = @mutex.synchronize { @entries.dup }
153
+ hist = { under_1ms: 0, under_5ms: 0, under_50ms: 0, under_200ms: 0, under_1s: 0, over_1s: 0 }
154
+ entries.each do |e|
155
+ key = if e.latency_ms < 1 then :under_1ms
156
+ elsif e.latency_ms < 5 then :under_5ms
157
+ elsif e.latency_ms < 50 then :under_50ms
158
+ elsif e.latency_ms < 200 then :under_200ms
159
+ elsif e.latency_ms < 1000 then :under_1s
160
+ else :over_1s
161
+ end
162
+ hist[key] += 1
163
+ end
164
+ hist
165
+ end
166
+
167
+ # Exports entries as JSON (for compliance/archival).
168
+ def export_json(since: nil)
169
+ entries = @mutex.synchronize { @entries.dup }
170
+ entries = entries.select { |e| e.timestamp >= since } if since
171
+ require "json"
172
+ JSON.pretty_generate(entries.map(&:to_h_ordered))
173
+ end
174
+
175
+ # Resets the audit trail (for testing). @internal
176
+ def reset
177
+ @mutex.synchronize do
178
+ @entries = []
179
+ @recent_event_ids = {}
180
+ @stats = @stats.transform_values { 0 }
181
+ end
182
+ end
183
+
184
+ private
185
+
186
+ def update_stats(entry)
187
+ source = entry.source.to_s
188
+ case source
189
+ when "internal"
190
+ @stats[:internal_decisions] += 1
191
+ @stats[:internal_latency_sum] += entry.latency_ms
192
+ when "external"
193
+ @stats[:external_decisions] += 1
194
+ @stats[:external_latency_sum] += entry.latency_ms
195
+ else
196
+ @stats[:hybrid_decisions] += 1
197
+ if entry.tier.to_i > 0
198
+ @stats[:internal_latency_sum] += entry.latency_ms
199
+ else
200
+ @stats[:external_latency_sum] += entry.latency_ms
201
+ end
202
+ end
203
+
204
+ @stats[:fallback_events] += 1 if entry.fallback_mode
205
+
206
+ case entry.decision.to_s
207
+ when "block" then @stats[:total_blocks] += 1
208
+ when "allow" then @stats[:total_allows] += 1
209
+ when "rate_limit" then @stats[:total_rate_limits] += 1
210
+ end
211
+ end
212
+ end
213
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevFortress
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevFortress
4
+ WebhookVerification = Struct.new(:valid, :reason) do
5
+ def valid?
6
+ valid
7
+ end
8
+ end
9
+ end