hooktrace 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.
- checksums.yaml +7 -0
- data/.rspec +1 -0
- data/.rubocop.yml +47 -0
- data/CHANGELOG.md +39 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +190 -0
- data/Rakefile +10 -0
- data/exe/hooktrace +9 -0
- data/lib/generators/hooktrace/install_generator.rb +29 -0
- data/lib/generators/hooktrace/templates/create_hooktrace_events.rb.erb +25 -0
- data/lib/hooktrace/cli.rb +139 -0
- data/lib/hooktrace/contract.rb +202 -0
- data/lib/hooktrace/contracts/paypal.json +8773 -0
- data/lib/hooktrace/contracts/stripe.json +29320 -0
- data/lib/hooktrace/error.rb +38 -0
- data/lib/hooktrace/event_record.rb +71 -0
- data/lib/hooktrace/field.rb +46 -0
- data/lib/hooktrace/importers/open_api_schema_converter.rb +158 -0
- data/lib/hooktrace/importers/paypal_open_api.rb +113 -0
- data/lib/hooktrace/importers/stripe_open_api.rb +118 -0
- data/lib/hooktrace/result.rb +38 -0
- data/lib/hooktrace/storage/active_record_store.rb +141 -0
- data/lib/hooktrace/storage/file_store.rb +103 -0
- data/lib/hooktrace/validator.rb +173 -0
- data/lib/hooktrace/version.rb +5 -0
- data/lib/hooktrace/web/assets/application.css +358 -0
- data/lib/hooktrace/web/views/contracts.erb +41 -0
- data/lib/hooktrace/web/views/event_detail.erb +53 -0
- data/lib/hooktrace/web/views/events.erb +100 -0
- data/lib/hooktrace/web/views/layout.erb +143 -0
- data/lib/hooktrace/web.rb +224 -0
- data/lib/hooktrace/webhook_processor.rb +171 -0
- data/lib/hooktrace.rb +273 -0
- data/sig/hooktrace.rbs +4 -0
- metadata +103 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "cgi"
|
|
4
|
+
require "erb"
|
|
5
|
+
require "json"
|
|
6
|
+
require "rack"
|
|
7
|
+
|
|
8
|
+
module Hooktrace
|
|
9
|
+
class Web
|
|
10
|
+
VIEWS_DIR = File.expand_path("web/views", __dir__).freeze
|
|
11
|
+
ASSETS_DIR = File.expand_path("web/assets", __dir__).freeze
|
|
12
|
+
|
|
13
|
+
def self.call(env)
|
|
14
|
+
new.call(env)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def call(env)
|
|
18
|
+
req = Rack::Request.new(env)
|
|
19
|
+
path = req.path_info.to_s
|
|
20
|
+
path = "/" if path.empty?
|
|
21
|
+
|
|
22
|
+
return forbidden_response(req) if req.post? && !origin_allowed?(req)
|
|
23
|
+
|
|
24
|
+
route_request(req, path)
|
|
25
|
+
rescue StandardError => e
|
|
26
|
+
handle_server_error(e)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
def route_request(req, path)
|
|
32
|
+
case [req.request_method, path]
|
|
33
|
+
when ["GET", "/"], ["GET", "/events"]
|
|
34
|
+
render_events(req)
|
|
35
|
+
when ["GET", "/contracts"]
|
|
36
|
+
render_contracts(req)
|
|
37
|
+
when ["POST", "/events/clear"]
|
|
38
|
+
Hooktrace.store.clear!
|
|
39
|
+
redirect_to(req, "/events")
|
|
40
|
+
when ["POST", "/events/revalidate_failed"]
|
|
41
|
+
Hooktrace.revalidate_failed
|
|
42
|
+
redirect_to(req, "/events")
|
|
43
|
+
else
|
|
44
|
+
handle_dynamic_route(req, path)
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def handle_dynamic_route(req, path)
|
|
49
|
+
if req.post? && path.match?(%r{\A/events/[^/]+/revalidate\z})
|
|
50
|
+
event_id = path.sub(%r{\A/events/([^/]+)/revalidate\z}, '\1')
|
|
51
|
+
revalidate_event(req, event_id)
|
|
52
|
+
elsif req.get? && path.start_with?("/events/")
|
|
53
|
+
render_event_detail(req, path.sub("/events/", ""))
|
|
54
|
+
else
|
|
55
|
+
[404, html_headers, ["<h1>404 Not Found</h1>"]]
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def revalidate_event(req, event_id)
|
|
60
|
+
outcome = Hooktrace.revalidate(event_id)
|
|
61
|
+
return json_revalidation_response(req, event_id, outcome) if wants_json?(req)
|
|
62
|
+
|
|
63
|
+
redirect_to(req, safe_return_path(req.params["return_to"]) || "/events/#{event_id}")
|
|
64
|
+
rescue Hooktrace::EventNotFoundError => e
|
|
65
|
+
if wants_json?(req)
|
|
66
|
+
return [404, json_headers, [JSON.generate(status: "not_found", event_id: event_id, message: e.message)]]
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
[404, html_headers, ["<h1>Event Not Found</h1>"]]
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def json_revalidation_response(req, event_id, outcome)
|
|
73
|
+
endpoint = "#{req.script_name}/events/#{event_id}/revalidate"
|
|
74
|
+
message = if outcome.valid?
|
|
75
|
+
"Event '#{event_id}' re-validated successfully against current contracts."
|
|
76
|
+
else
|
|
77
|
+
"Event '#{event_id}' re-validated with #{outcome.errors.size} contract violation(s)."
|
|
78
|
+
end
|
|
79
|
+
payload = outcome.to_h.merge(api: "POST #{endpoint}", message: message, stats: Hooktrace.store.stats)
|
|
80
|
+
[200, json_headers, [JSON.generate(payload)]]
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def wants_json?(req)
|
|
84
|
+
req.env["HTTP_ACCEPT"].to_s.include?("application/json")
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def safe_return_path(path)
|
|
88
|
+
return nil if path.nil? || path.empty?
|
|
89
|
+
return path if path.start_with?("/events") && !path.start_with?("//")
|
|
90
|
+
|
|
91
|
+
nil
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def render_events(req)
|
|
95
|
+
status_filter = req.params["status"]
|
|
96
|
+
type_filter = req.params["type"]
|
|
97
|
+
events = Hooktrace.store.all(limit: 100, event_type: type_filter, status: status_filter)
|
|
98
|
+
stats = Hooktrace.store.stats
|
|
99
|
+
|
|
100
|
+
render_page(
|
|
101
|
+
req,
|
|
102
|
+
title: "Events",
|
|
103
|
+
template: :events,
|
|
104
|
+
locals: {
|
|
105
|
+
events: events,
|
|
106
|
+
stats: stats,
|
|
107
|
+
contracts_count: Hooktrace.registry.size,
|
|
108
|
+
status_filter: status_filter,
|
|
109
|
+
base_path: req.script_name.to_s
|
|
110
|
+
}
|
|
111
|
+
)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def render_contracts(req)
|
|
115
|
+
render_page(
|
|
116
|
+
req,
|
|
117
|
+
title: "Contracts",
|
|
118
|
+
template: :contracts,
|
|
119
|
+
locals: { contracts: Hooktrace.registry.values }
|
|
120
|
+
)
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def render_event_detail(req, event_id)
|
|
124
|
+
event = Hooktrace.store.find(event_id)
|
|
125
|
+
return [404, html_headers, ["<h1>Event Not Found</h1>"]] unless event
|
|
126
|
+
|
|
127
|
+
render_page(
|
|
128
|
+
req,
|
|
129
|
+
title: "Event #{event.id}",
|
|
130
|
+
template: :event_detail,
|
|
131
|
+
locals: { event: event, base_path: req.script_name.to_s }
|
|
132
|
+
)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def render_page(req, title:, template:, locals: {})
|
|
136
|
+
content = render_erb(template, locals)
|
|
137
|
+
active_tab = title.downcase.include?("contract") ? "contracts" : "events"
|
|
138
|
+
|
|
139
|
+
html = render_erb(
|
|
140
|
+
:layout,
|
|
141
|
+
title: title,
|
|
142
|
+
active_tab: active_tab,
|
|
143
|
+
base_path: req.script_name.to_s,
|
|
144
|
+
stylesheet: stylesheet,
|
|
145
|
+
content: content
|
|
146
|
+
)
|
|
147
|
+
[200, html_headers, [html]]
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
def render_erb(name, locals = {})
|
|
151
|
+
template_path = File.join(VIEWS_DIR, "#{name}.erb")
|
|
152
|
+
erb = ERB.new(File.read(template_path, encoding: "UTF-8"), trim_mode: "-")
|
|
153
|
+
ctx = WebTemplateContext.new(locals)
|
|
154
|
+
erb.result(ctx.template_binding)
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def stylesheet
|
|
158
|
+
@stylesheet ||= File.read(File.join(ASSETS_DIR, "application.css"), encoding: "UTF-8")
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def origin_allowed?(req)
|
|
162
|
+
origin = req.env["HTTP_ORIGIN"] || req.env["HTTP_REFERER"]
|
|
163
|
+
return true if origin.nil? || origin.empty?
|
|
164
|
+
|
|
165
|
+
begin
|
|
166
|
+
parsed = URI.parse(origin)
|
|
167
|
+
rescue URI::InvalidURIError
|
|
168
|
+
return true
|
|
169
|
+
end
|
|
170
|
+
return true unless parsed&.host
|
|
171
|
+
|
|
172
|
+
parsed.host == req.host
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
def forbidden_response(req)
|
|
176
|
+
msg = "Cross-origin request blocked"
|
|
177
|
+
return [403, json_headers, [JSON.generate(error: msg)]] if wants_json?(req)
|
|
178
|
+
|
|
179
|
+
[403, html_headers, ["<h1>403 Forbidden</h1><p>#{h(msg)}</p>"]]
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def handle_server_error(err)
|
|
183
|
+
env_mode = ENV["RACK_ENV"] || ENV["RAILS_ENV"] || "development"
|
|
184
|
+
body = if %w[development test].include?(env_mode)
|
|
185
|
+
"<h1>Hooktrace::Web Error</h1><pre>#{h(err.full_message)}</pre>"
|
|
186
|
+
else
|
|
187
|
+
"<h1>500 Internal Server Error</h1><p>An unexpected error occurred in Hooktrace::Web.</p>"
|
|
188
|
+
end
|
|
189
|
+
[500, html_headers, [body]]
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def redirect_to(req, path)
|
|
193
|
+
[302, { "location" => "#{req.script_name}#{path}" }, []]
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
def html_headers
|
|
197
|
+
{ "content-type" => "text/html; charset=utf-8" }
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
def json_headers
|
|
201
|
+
{ "content-type" => "application/json; charset=utf-8" }
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
def h(value)
|
|
205
|
+
CGI.escapeHTML(value.to_s)
|
|
206
|
+
end
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
class WebTemplateContext
|
|
210
|
+
def initialize(locals)
|
|
211
|
+
locals.each do |key, value|
|
|
212
|
+
define_singleton_method(key) { value }
|
|
213
|
+
end
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
def h(value)
|
|
217
|
+
CGI.escapeHTML(value.to_s)
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
def template_binding
|
|
221
|
+
binding
|
|
222
|
+
end
|
|
223
|
+
end
|
|
224
|
+
end
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "securerandom"
|
|
5
|
+
|
|
6
|
+
module Hooktrace
|
|
7
|
+
class InvalidPayloadError < StandardError; end
|
|
8
|
+
|
|
9
|
+
class WebhookOutcome
|
|
10
|
+
attr_reader :result, :provider, :event_id, :event_type, :matched_contracts
|
|
11
|
+
|
|
12
|
+
def initialize(result:, provider:, event_id:, event_type:, matched_contracts:)
|
|
13
|
+
@result = result
|
|
14
|
+
@provider = provider
|
|
15
|
+
@event_id = event_id
|
|
16
|
+
@event_type = event_type
|
|
17
|
+
@matched_contracts = matched_contracts.freeze
|
|
18
|
+
freeze
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def valid?
|
|
22
|
+
result.valid?
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def invalid?
|
|
26
|
+
result.invalid?
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def errors
|
|
30
|
+
result.errors
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def to_h
|
|
34
|
+
{
|
|
35
|
+
status: valid? ? "success" : "contract_violation",
|
|
36
|
+
provider: provider,
|
|
37
|
+
event_id: event_id,
|
|
38
|
+
event_type: event_type,
|
|
39
|
+
valid: valid?,
|
|
40
|
+
matched_contracts: matched_contracts,
|
|
41
|
+
errors: errors.map(&:to_h)
|
|
42
|
+
}
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
class WebhookProcessor
|
|
47
|
+
def self.process(payload_or_raw, headers: {}, provider: nil, event_type: nil, id: nil,
|
|
48
|
+
strict: false, record: Hooktrace.auto_record)
|
|
49
|
+
new.process(
|
|
50
|
+
payload_or_raw,
|
|
51
|
+
headers: headers,
|
|
52
|
+
provider: provider,
|
|
53
|
+
event_type: event_type,
|
|
54
|
+
id: id,
|
|
55
|
+
strict: strict,
|
|
56
|
+
record: record
|
|
57
|
+
)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def process(payload_or_raw, headers: {}, provider: nil, event_type: nil, id: nil,
|
|
61
|
+
strict: false, record: Hooktrace.auto_record)
|
|
62
|
+
payload = parse_payload(payload_or_raw)
|
|
63
|
+
norm_headers = normalize_headers(headers)
|
|
64
|
+
|
|
65
|
+
resolved_provider = (provider || detect_provider(payload, norm_headers)).to_s
|
|
66
|
+
resolved_type = (event_type || extract_event_type(payload, norm_headers, resolved_provider)).to_s
|
|
67
|
+
resolved_id = (id || extract_event_id(payload, norm_headers)).to_s
|
|
68
|
+
|
|
69
|
+
contracts = match_contracts(resolved_provider, resolved_type)
|
|
70
|
+
result = validate_or_record_unmatched(
|
|
71
|
+
contracts, payload,
|
|
72
|
+
provider: resolved_provider, event_type: resolved_type, id: resolved_id,
|
|
73
|
+
strict: strict, record: record
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
WebhookOutcome.new(
|
|
77
|
+
result: result,
|
|
78
|
+
provider: resolved_provider,
|
|
79
|
+
event_id: resolved_id,
|
|
80
|
+
event_type: resolved_type,
|
|
81
|
+
matched_contracts: contracts
|
|
82
|
+
)
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
private
|
|
86
|
+
|
|
87
|
+
def parse_payload(payload_or_raw)
|
|
88
|
+
parsed = payload_or_raw.is_a?(String) ? JSON.parse(payload_or_raw) : payload_or_raw
|
|
89
|
+
raise InvalidPayloadError, "Webhook payload must be a JSON object (Hash)" unless parsed.is_a?(Hash)
|
|
90
|
+
|
|
91
|
+
parsed
|
|
92
|
+
rescue JSON::ParserError => e
|
|
93
|
+
raise InvalidPayloadError, "Invalid JSON payload: #{e.message}"
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
def normalize_headers(headers)
|
|
97
|
+
return {} unless headers.respond_to?(:each)
|
|
98
|
+
|
|
99
|
+
headers.each_with_object({}) do |(key, val), acc|
|
|
100
|
+
next unless key.is_a?(String) || key.is_a?(Symbol)
|
|
101
|
+
|
|
102
|
+
normalized = key.to_s.downcase.sub(/\Ahttp_/, "").tr("_", "-")
|
|
103
|
+
acc[normalized] = val
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def detect_provider(payload, headers)
|
|
108
|
+
if headers.key?("stripe-signature") || payload["object"] == "event"
|
|
109
|
+
"stripe"
|
|
110
|
+
elsif headers.key?("paypal-auth-algo") || (payload["resource_type"] && payload["event_type"])
|
|
111
|
+
"paypal"
|
|
112
|
+
else
|
|
113
|
+
"unknown"
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def extract_event_type(payload, _headers, provider)
|
|
118
|
+
case provider
|
|
119
|
+
when "stripe" then payload["type"] || "unknown"
|
|
120
|
+
when "paypal" then payload["event_type"] || "unknown"
|
|
121
|
+
else payload["event_type"] || payload["type"] || "unknown"
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def extract_event_id(payload, headers)
|
|
126
|
+
payload["id"] || headers["paypal-transmission-id"] || SecureRandom.hex(8)
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
def match_contracts(provider, event_type)
|
|
130
|
+
ensure_provider_loaded(provider)
|
|
131
|
+
|
|
132
|
+
matched = []
|
|
133
|
+
base = "#{provider}.event.base"
|
|
134
|
+
matched << base if Hooktrace.registry.key?(base)
|
|
135
|
+
|
|
136
|
+
if event_type && !event_type.empty? && event_type != "unknown"
|
|
137
|
+
specific = find_matching_contract(provider, event_type)
|
|
138
|
+
matched << specific if specific
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
matched.uniq
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def ensure_provider_loaded(provider)
|
|
145
|
+
return if Hooktrace.registry.keys.any? { |k| k.start_with?("#{provider}.") }
|
|
146
|
+
|
|
147
|
+
Hooktrace.load_builtin_contracts!(provider) if Hooktrace.builtin_providers.include?(provider)
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
def find_matching_contract(provider, event_type)
|
|
151
|
+
["#{provider}.#{event_type}", event_type].find { |name| Hooktrace.registry.key?(name) }
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def validate_or_record_unmatched(contracts, payload, provider:, event_type:, id:, strict:, record:)
|
|
155
|
+
if contracts.any?
|
|
156
|
+
return Hooktrace.validate(
|
|
157
|
+
contracts, payload,
|
|
158
|
+
strict: strict, record: record, id: id, event_type: event_type, provider: provider
|
|
159
|
+
)
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
result = Result.new(errors: [])
|
|
163
|
+
if record
|
|
164
|
+
Hooktrace.store.save(
|
|
165
|
+
EventRecord.new(id: id, event_type: event_type, provider: provider, valid: true, errors: [], payload: payload)
|
|
166
|
+
)
|
|
167
|
+
end
|
|
168
|
+
result
|
|
169
|
+
end
|
|
170
|
+
end
|
|
171
|
+
end
|
data/lib/hooktrace.rb
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "monitor"
|
|
4
|
+
require_relative "hooktrace/version"
|
|
5
|
+
require_relative "hooktrace/error"
|
|
6
|
+
require_relative "hooktrace/field"
|
|
7
|
+
require_relative "hooktrace/result"
|
|
8
|
+
require_relative "hooktrace/validator"
|
|
9
|
+
require_relative "hooktrace/contract"
|
|
10
|
+
require_relative "hooktrace/event_record"
|
|
11
|
+
require_relative "hooktrace/storage/file_store"
|
|
12
|
+
require_relative "hooktrace/storage/active_record_store"
|
|
13
|
+
require_relative "hooktrace/importers/stripe_open_api"
|
|
14
|
+
require_relative "hooktrace/importers/paypal_open_api"
|
|
15
|
+
require_relative "hooktrace/webhook_processor"
|
|
16
|
+
require_relative "hooktrace/web"
|
|
17
|
+
|
|
18
|
+
module Hooktrace
|
|
19
|
+
class StandardError < ::StandardError; end
|
|
20
|
+
class ContractNotFoundError < StandardError; end
|
|
21
|
+
class EventNotFoundError < StandardError; end
|
|
22
|
+
|
|
23
|
+
BUILTIN_CONTRACTS_DIR = File.expand_path("hooktrace/contracts", __dir__).freeze
|
|
24
|
+
|
|
25
|
+
@registry = {}
|
|
26
|
+
@registry_mutex = Monitor.new
|
|
27
|
+
@store = nil
|
|
28
|
+
@store_mutex = Monitor.new
|
|
29
|
+
@auto_record = true
|
|
30
|
+
|
|
31
|
+
class << self
|
|
32
|
+
attr_accessor :auto_record
|
|
33
|
+
|
|
34
|
+
def registry
|
|
35
|
+
@registry_mutex.synchronize { @registry.dup }
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def builtin_contracts_path
|
|
39
|
+
BUILTIN_CONTRACTS_DIR
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def builtin_providers
|
|
43
|
+
Dir.glob(File.join(BUILTIN_CONTRACTS_DIR, "*.json")).map do |file|
|
|
44
|
+
File.basename(file, ".json")
|
|
45
|
+
end.sort
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def load_builtin_contracts!(*providers)
|
|
49
|
+
targets = providers.flatten.compact.map(&:to_s)
|
|
50
|
+
if targets.empty?
|
|
51
|
+
load_contracts_from(BUILTIN_CONTRACTS_DIR)
|
|
52
|
+
else
|
|
53
|
+
targets.flat_map do |provider|
|
|
54
|
+
path = File.join(BUILTIN_CONTRACTS_DIR, "#{provider}.json")
|
|
55
|
+
File.exist?(path) ? Array(load_contract(path)) : []
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def sync_contracts!(provider = :all, output: nil, events: nil, spec_source: nil)
|
|
61
|
+
case provider.to_s
|
|
62
|
+
when "all"
|
|
63
|
+
{ "stripe" => sync_contracts!(:stripe, events: events), "paypal" => sync_contracts!(:paypal, events: events) }
|
|
64
|
+
when "stripe"
|
|
65
|
+
sync_provider_bundle(Importers::StripeOpenApi, "stripe.json", :spec_source,
|
|
66
|
+
output: output, events: events, spec_source: spec_source)
|
|
67
|
+
when "paypal"
|
|
68
|
+
sync_provider_bundle(Importers::PaypalOpenApi, "paypal.json", :spec_base,
|
|
69
|
+
output: output, events: events, spec_source: spec_source)
|
|
70
|
+
else
|
|
71
|
+
raise ArgumentError, "Unsupported sync provider '#{provider}'. Supported: stripe, paypal, all"
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def store
|
|
76
|
+
@store_mutex.synchronize do
|
|
77
|
+
@store ||= Storage::ActiveRecordStore.available? ? Storage::ActiveRecordStore.new : Storage::FileStore.new
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def store=(new_store)
|
|
82
|
+
@store_mutex.synchronize { @store = new_store }
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def configure
|
|
86
|
+
yield self
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def contracts_path=(directory)
|
|
90
|
+
load_contracts_from(directory) if directory && Dir.exist?(directory)
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def define(name, &)
|
|
94
|
+
contract = Contract.define(name, &)
|
|
95
|
+
@registry_mutex.synchronize { @registry[name.to_s] = contract }
|
|
96
|
+
contract
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def override(name, &)
|
|
100
|
+
@registry_mutex.synchronize do
|
|
101
|
+
existing = fetch_or_load_contract(name)
|
|
102
|
+
updated = Contract.override(existing, &)
|
|
103
|
+
@registry[updated.name] = updated
|
|
104
|
+
updated
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def contract(name)
|
|
109
|
+
@registry_mutex.synchronize do
|
|
110
|
+
fetch_or_load_contract(name)
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
alias [] contract
|
|
114
|
+
|
|
115
|
+
def validate(name_or_contracts, payload, strict: false, record: @auto_record,
|
|
116
|
+
id: nil, event_type: nil, provider: nil)
|
|
117
|
+
contracts = resolve_contracts(name_or_contracts)
|
|
118
|
+
all_errors = contracts.flat_map { |c| c.validate(payload, strict: strict).errors }.uniq
|
|
119
|
+
result = Result.new(errors: all_errors)
|
|
120
|
+
|
|
121
|
+
save_validation_record(result, contracts, payload, id: id, event_type: event_type, provider: provider) if record
|
|
122
|
+
result
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def record_and_validate(name_or_contracts, payload, strict: false, id: nil, event_type: nil, provider: nil)
|
|
126
|
+
contracts = resolve_contracts(name_or_contracts)
|
|
127
|
+
all_errors = contracts.flat_map { |c| c.validate(payload, strict: strict).errors }.uniq
|
|
128
|
+
result = Result.new(errors: all_errors)
|
|
129
|
+
|
|
130
|
+
record = save_validation_record(result, contracts, payload, id: id, event_type: event_type, provider: provider)
|
|
131
|
+
[result, record]
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def process_webhook(payload_or_raw, headers: {}, provider: nil, event_type: nil, id: nil,
|
|
135
|
+
strict: false, record: @auto_record)
|
|
136
|
+
WebhookProcessor.process(
|
|
137
|
+
payload_or_raw,
|
|
138
|
+
headers: headers,
|
|
139
|
+
provider: provider,
|
|
140
|
+
event_type: event_type,
|
|
141
|
+
id: id,
|
|
142
|
+
strict: strict,
|
|
143
|
+
record: record
|
|
144
|
+
)
|
|
145
|
+
end
|
|
146
|
+
alias handle_webhook process_webhook
|
|
147
|
+
|
|
148
|
+
def revalidate(event_id)
|
|
149
|
+
record = store.find(event_id)
|
|
150
|
+
raise EventNotFoundError, "Event '#{event_id}' not found" unless record
|
|
151
|
+
|
|
152
|
+
process_webhook(
|
|
153
|
+
record.payload,
|
|
154
|
+
provider: record.provider,
|
|
155
|
+
event_type: record.event_type,
|
|
156
|
+
id: record.id,
|
|
157
|
+
record: true
|
|
158
|
+
)
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def revalidate_failed(limit: 1000)
|
|
162
|
+
failed = store.all(limit: limit, status: "invalid")
|
|
163
|
+
passed = failed.count { |event| revalidate(event.id).valid? }
|
|
164
|
+
{ total: failed.size, passed: passed, still_failed: failed.size - passed }
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def load_contract(path)
|
|
168
|
+
content = File.read(path, encoding: "UTF-8")
|
|
169
|
+
data = JSON.parse(content)
|
|
170
|
+
contracts = parse_contracts_data(data)
|
|
171
|
+
|
|
172
|
+
@registry_mutex.synchronize do
|
|
173
|
+
contracts.each do |c|
|
|
174
|
+
@registry[c.name] = c
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
single_contract?(data, contracts) ? contracts.first : contracts
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
def load_contracts_from(directory)
|
|
182
|
+
pattern = File.join(directory, "**", "*.json")
|
|
183
|
+
Dir.glob(pattern).flat_map { |file| Array(load_contract(file)) }
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
def clear_registry!
|
|
187
|
+
@registry_mutex.synchronize { @registry.clear }
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
private
|
|
191
|
+
|
|
192
|
+
def parse_contracts_data(data)
|
|
193
|
+
if data.is_a?(Array)
|
|
194
|
+
data.map { |item| Contract.from_h(item) }
|
|
195
|
+
elsif data.key?("events") || data.key?("contracts")
|
|
196
|
+
list = data["events"] || data["contracts"]
|
|
197
|
+
prefix = data["provider"]
|
|
198
|
+
list.map do |item|
|
|
199
|
+
item["name"] = "#{prefix}.#{item["name"]}" if prefix && !item["name"].start_with?("#{prefix}.")
|
|
200
|
+
Contract.from_h(item)
|
|
201
|
+
end
|
|
202
|
+
elsif data.key?("fields")
|
|
203
|
+
[Contract.from_h(data)]
|
|
204
|
+
else
|
|
205
|
+
data.map do |name, definition|
|
|
206
|
+
Contract.from_h(definition.merge("name" => name))
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
def sync_provider_bundle(importer, default_filename, source_key, output:, events:, spec_source:)
|
|
212
|
+
target = output || File.join(BUILTIN_CONTRACTS_DIR, default_filename)
|
|
213
|
+
opts = { output_path: target }
|
|
214
|
+
opts[:events] = events unless events.nil?
|
|
215
|
+
opts[source_key] = spec_source if spec_source
|
|
216
|
+
|
|
217
|
+
bundle = importer.sync(**opts)
|
|
218
|
+
load_contract(target)
|
|
219
|
+
bundle
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
def fetch_or_load_contract(name)
|
|
223
|
+
str_name = name.to_s
|
|
224
|
+
return @registry[str_name] if @registry.key?(str_name)
|
|
225
|
+
|
|
226
|
+
# Attempt on-demand auto-load of built-in provider bundle
|
|
227
|
+
provider = str_name.split(".").first
|
|
228
|
+
builtin_file = File.join(BUILTIN_CONTRACTS_DIR, "#{provider}.json")
|
|
229
|
+
load_contract(builtin_file) if File.exist?(builtin_file)
|
|
230
|
+
|
|
231
|
+
@registry[str_name] || raise(ContractNotFoundError, "Contract '#{name}' is not defined")
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
def single_contract?(data, contracts)
|
|
235
|
+
contracts.size == 1 && !data.is_a?(Array) && !data.key?("events") && !data.key?("contracts")
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
def resolve_contracts(name_or_contracts)
|
|
239
|
+
Array(name_or_contracts).compact.map do |item|
|
|
240
|
+
item.is_a?(Contract) ? item : contract(item)
|
|
241
|
+
end
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
def save_validation_record(result, contracts, payload, id: nil, event_type: nil, provider: nil)
|
|
245
|
+
resolved_type = event_type || resolve_event_type(contracts, payload)
|
|
246
|
+
record = EventRecord.new(
|
|
247
|
+
id: id || extract_event_id(payload),
|
|
248
|
+
event_type: resolved_type,
|
|
249
|
+
provider: provider,
|
|
250
|
+
valid: result.valid?,
|
|
251
|
+
errors: result.errors.map(&:to_h),
|
|
252
|
+
payload: payload
|
|
253
|
+
)
|
|
254
|
+
store.save(record)
|
|
255
|
+
record
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def resolve_event_type(contracts, payload)
|
|
259
|
+
specific = contracts.last&.name
|
|
260
|
+
return specific unless specific&.end_with?(".event.base") && payload.is_a?(Hash)
|
|
261
|
+
|
|
262
|
+
payload["type"] || payload[:type] || payload["event_type"] || payload[:event_type] || specific
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
def extract_event_id(payload)
|
|
266
|
+
return SecureRandom.hex(8) unless payload.is_a?(Hash)
|
|
267
|
+
|
|
268
|
+
(payload["id"] || payload[:id] || SecureRandom.hex(8)).to_s
|
|
269
|
+
end
|
|
270
|
+
end
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
HookTrace = Hooktrace
|
data/sig/hooktrace.rbs
ADDED